#include "memory.h" #include #include #include #include #include #include #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; }