diff options
| author | Sam Light <sam@lightscale.co.uk> | 2025-09-10 19:37:28 +0100 |
|---|---|---|
| committer | Sam Light <sam@lightscale.co.uk> | 2025-09-10 19:37:28 +0100 |
| commit | 4d3e462531d2172cb13319c7f79c0e2228e652fa (patch) | |
| tree | 6381426e806b30814890e74085afef17e3ee78f3 /src/modules/cpu.c | |
| parent | b74a383e6ded85c122f98137936d78f768f8f938 (diff) | |
Big update
Diffstat (limited to 'src/modules/cpu.c')
| -rw-r--r-- | src/modules/cpu.c | 88 |
1 files changed, 88 insertions, 0 deletions
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 <stdlib.h> +#include <string.h> +#include <stdio.h> +#include <unistd.h> +#include <inttypes.h> +#include <tgmath.h> + +#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; +} |
