status-mem/mem.c
author Stiletto <blasux@blasux.ru>
Wed, 10 Dec 2014 20:31:21 +0400
changeset 13 d7ce3b1dddc4
parent 3 dae770da6416
child 15 163e96e2b941
permissions -rw-r--r--
Proper colors

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

#include "config.h"

int
main(void)
{
    while (1) {
        char line[513];
        FILE *fd;

        fd = fopen("/proc/meminfo", "r");
        if (fd == NULL) {
            perror("fopen");
            exit(1);
        }

        int free = 0;
        int total = 0;
        int sub;
        while (!feof(fd)) {
            if (fgets(line, sizeof(line)-1, fd) == NULL)
                break;

            if (!strncmp(line, "MemTotal", 8))
                sscanf(line+9, "%*[ ]%d%*[^\n]", &total);

            if (!strncmp(line, "MemFree", 7))
                sscanf(line+8, "%*[ ]%d%*[^\n]", &free);

            if (!strncmp(line, "Buffers", 7)) {
                sscanf(line+8, "%*[ ]%d%*[^\n]", &sub);
                free += sub;
            }
            if (!strncmp(line, "Cached", 6)) {
                sscanf(line+7, "%*[ ]%d%*[^\n]", &sub);
                free += sub;
            }
        }
        fclose(fd);

        int used = total - free;

#ifdef PANGO_MARKUP
        char *color;
        if (used*1.0/total < GREEN) color = "color='#0f0'";
        else if (used*1.0/total > RED) color = "color='#f33'";
        else if (used*1.0/total > ORANGE) color = "color='#fa0'";
        else color = "";
        printf("<span %s>%d/%d</span>\n", color, used/1024, total/1024);
#else
        printf("%d/%d\n", used/1024, total/1024);
#endif
        fflush(stdout);
	sleep(UPDATE_PERIOD);
    }
}