From 4d3e462531d2172cb13319c7f79c0e2228e652fa Mon Sep 17 00:00:00 2001 From: Sam Light Date: Wed, 10 Sep 2025 19:37:28 +0100 Subject: Big update --- src/modules/cpu.c | 88 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 src/modules/cpu.c (limited to 'src/modules/cpu.c') diff --git a/src/modules/cpu.c b/src/modules/cpu.c new file mode 100644 index 0000000..cf70524 --- /dev/null +++ b/src/modules/cpu.c @@ -0,0 +1,88 @@ +#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; +} -- cgit v1.2.3