summaryrefslogtreecommitdiff
path: root/src/modules/memory.c
diff options
context:
space:
mode:
authorSam Light <sam@lightscale.co.uk>2025-09-10 19:37:28 +0100
committerSam Light <sam@lightscale.co.uk>2025-09-10 19:37:28 +0100
commit4d3e462531d2172cb13319c7f79c0e2228e652fa (patch)
tree6381426e806b30814890e74085afef17e3ee78f3 /src/modules/memory.c
parentb74a383e6ded85c122f98137936d78f768f8f938 (diff)
Big update
Diffstat (limited to 'src/modules/memory.c')
-rw-r--r--src/modules/memory.c91
1 files changed, 91 insertions, 0 deletions
diff --git a/src/modules/memory.c b/src/modules/memory.c
new file mode 100644
index 0000000..b9230da
--- /dev/null
+++ b/src/modules/memory.c
@@ -0,0 +1,91 @@
+#include "memory.h"
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdbool.h>
+#include <inttypes.h>
+#include <tgmath.h>
+
+#define FILE_MEMINFO_PATH "/proc/meminfo"
+
+#define VALUE_SIZE 32
+
+struct memory {
+ FILE * memfd;
+ char value[VALUE_SIZE];
+};
+
+struct memory_info {
+ unsigned long total;
+ unsigned long avaliable;
+ unsigned short found;
+};
+
+struct memory *
+memory_new()
+{
+ struct memory * m = malloc(sizeof(struct memory));
+
+ m->memfd = fopen(FILE_MEMINFO_PATH, "r");
+
+ return m;
+}
+
+void
+memory_free(struct memory * m)
+{
+ free(m);
+}
+
+static char *
+find_mem_value(char * line, const char * key)
+{
+ size_t klen = strlen(key);
+ if(strncmp(line, key, klen) == 0) {
+ return line + klen;
+ }
+ return NULL;
+}
+
+void
+memory_update(struct memory * m)
+{
+ const unsigned short lsize = 512;
+ char line[lsize];
+ char * val;
+
+ bool found_total = false, found_available = false;
+ unsigned long total = 0, available = 0;
+
+ unsigned short percent = 0;
+
+ rewind(m->memfd);
+ fflush(m->memfd);
+
+ while((!found_total || !found_available) && !feof(m->memfd)) {
+ fgets(line, lsize, m->memfd);
+
+ val = find_mem_value(line, "MemTotal: ");
+ if(!found_total && val != NULL) {
+ found_total = true;
+ total = strtoul(val, NULL, 10);
+ }
+
+ val = find_mem_value(line, "MemAvailable: ");
+ if(!found_available && val != NULL) {
+ found_available = true;
+ available = strtoul(val, NULL, 10);
+ }
+ }
+
+ percent = round((100.0f / total) * (total - available));
+
+ snprintf(m->value, VALUE_SIZE, "\uf538% 4d%%", percent);
+}
+
+const char *
+memory_get_val(struct memory * m)
+{
+ return m->value;
+}