#include "cpu.h" #include #include #include #include #include #include #define VALUE_SIZE 32 #define FILE_STAT_PATH "/proc/stat" struct cpu_stat { unsigned long usage; unsigned long total; }; struct cpu { char value[VALUE_SIZE]; struct cpu_stat last; FILE * statfd; }; static void parse_cpu_stat(struct cpu * c, struct cpu_stat * stat) { char line[1024]; char * tok = line + 5; stat->usage = 0; stat->total = 0; rewind(c->statfd); fflush(c->statfd); fgets(line, 1024, c->statfd); stat->usage += strtoul(tok, &tok, 10); stat->usage += strtoul(tok, &tok, 10); stat->usage += strtoul(tok, &tok, 10); stat->total += stat->usage + strtoul(tok, &tok, 10); } struct cpu * cpu_new() { struct cpu * c = malloc(sizeof(struct cpu)); memset(c->value, '\0', VALUE_SIZE); c->statfd = fopen(FILE_STAT_PATH, "r"); parse_cpu_stat(c, &c->last); return c; } void cpu_free(struct cpu * c) { fclose(c->statfd); free(c); } void cpu_update(struct cpu * c) { struct cpu_stat stat; unsigned long usage_diff, total_diff; unsigned short percent; parse_cpu_stat(c, &stat); usage_diff = stat.usage - c->last.usage; total_diff = stat.total - c->last.total; c->last = stat; percent = round((100.0f / total_diff) * usage_diff); snprintf(c->value, VALUE_SIZE, "\uf2db% 4d%%", percent); } const char * cpu_get_val(struct cpu * c) { return c->value; }