Last active
November 11, 2021 11:28
-
-
Save radito3/8cbb02b6d50bbc5885b70f46daea4e45 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <sys/types.h> | |
#include <sys/sysinfo.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <fcntl.h> | |
#include <unistd.h> | |
#include <sys/socket.h> | |
double get_cpu_utilization() { | |
unsigned long long totalUser, totalNice, totalSys, totalIdle, totalIOWait, totalIrq, totalSoftirq, total; | |
FILE* file = fopen("/proc/stat", "r"); | |
fscanf(file, "cpu %llu %llu %llu %llu %llu %llu %llu", &totalUser, &totalNice, | |
&totalSys, &totalIdle, &totalIOWait, &totalIrq, &totalSoftirq); | |
fclose(file); | |
total = totalUser + totalNice + totalSys + totalIdle + totalIOWait + totalIrq + totalSoftirq; | |
return 100.0 - ((totalIdle * 100.0) / total); | |
} | |
long long get_free_memory() { | |
struct sysinfo mem_info; | |
sysinfo(&mem_info); | |
long long phys_mem_used = mem_info.totalram - mem_info.freeram; | |
phys_mem_used *= mem_info.mem_unit; | |
return phys_mem_used; | |
} | |
int main(int argc, char* argv[]) { | |
long long phys_mem_used = get_free_memory(); | |
double cpu_util = get_cpu_utilization(); | |
char result[512]; | |
sprintf(result, "{\"cpu\":\"%f\",\"memory\":\"%ll\"}\0", cpu_util, phys_mem_used); | |
if (argc == 1) { | |
printf(result); | |
return 0; | |
} | |
long socket_fd = strtol(argv[1], NULL, 10); | |
send(socket_fd, result, strlen(result), 0); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment