1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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;
}
|