summaryrefslogtreecommitdiff
path: root/src/status/memusage.c
blob: 18d57a19ce49d1c0a7c02b32efd55dadb801b769 (plain)
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "common.h"
#include "tools.h"


void status_memusage(GlobalData *g)
{
  StatusItem s;
  char text[16] = { 0 };

  char *stline = NULL;
  size_t stlen;
  FILE *stfile;

  long long memtotal = 0;
  long long memfree = 0;
  long long memused;
  long long membuffers = 0;
  long long memcached = 0;
  long long slab_reclaimable = 0;


  statusitem_init(&s);
  s.text = text;

  stfile = fopen("/proc/meminfo", "r");
  if (stfile != NULL) {
    stlen = getline(&stline, &stlen, stfile);
    memtotal = atoll(&stline[16]);

    stlen = getline(&stline, &stlen, stfile);
    memfree = atoll(&stline[16]);

    stlen = getline(&stline, &stlen, stfile);
    if (stlen > 13 && !memcmp(stline, "MemAvailable:", 13)) {
      stlen = getline(&stline, &stlen, stfile);
    }
    membuffers = atoll(&stline[16]);

    stlen = getline(&stline, &stlen, stfile);
    memcached = atoll(&stline[16]);

    while (0 < (stlen = getline(&stline, &stlen, stfile))) {
      if (stlen > 13 && !memcmp(stline, "SReclaimable:", 13)) {
        slab_reclaimable = atoll(&stline[16]);
        break;
      }
    }

    free(stline);
    fclose(stfile);

    memused = memtotal - memfree - memcached - slab_reclaimable - membuffers;

    memused /= 1024;	// Just show MBs used

    /* Change color based on % of RAM used */
    if ((float)memused / (float)memtotal < 0.85) {
      s.color = "#22FF22";  // green
    } else {
      s.color = "#FF0000";  // red
    }

    snprintf(text, sizeof(text), "Mem: %lld M", memused);

    line_append_item(g, &s);
  }
}