#include #include #include #include #include "parser.h" static int str_to_dec(char *src, char **dst) { int ret; while(((*src < '0') || (*src > '9')) && *src) src++; ret = atoi(src); if (dst) { while(((*src >= '0') && (*src <= '9')) && *src) src++; *dst = src; } return ret; } static int get_word(char *src, char **dst, char *word) { int ret = 0; while(((*src == ' ') || (*src == '\t')) && *src) src++; while(((*src != ' ') && (*src != '\t')) && *src) { *word = *src; word++; src++; ret++; } *word = 0; if (dst) *dst = src; return ret; } #define STATFILE "/proc/stat" int cpu_parser(char *data) { char buf[1024]; char *str = buf; FILE *file = fopen(STATFILE, "r"); int user, nice, sys, idle, wait, irq, softirq; if (file == NULL) { fprintf(stderr, "Failed to open file %s\n", STATFILE); return -1; } if (!fgets(buf, 1024, file)) { fprintf(stderr, "Failed to read file %s\n", STATFILE); fclose(file); return -1; } user = str_to_dec(str, &str); nice = str_to_dec(str, &str); sys = str_to_dec(str, &str); idle = str_to_dec(str, &str); wait = str_to_dec(str, &str); irq = str_to_dec(str, &str); softirq = str_to_dec(str, &str); sprintf(data, "%d:%d:%d:%d:%d:%d:%d", user, nice, sys, idle, wait, irq, softirq); fclose(file); return 0; } #define MEMFILE "/proc/meminfo" int mem_parser(char *data) { char buf[1024], word[1024]; int free = 0, buffered = 0, cache = 0, active = 0, inactive = 0, swapfree = 0, anon = 0, slab = 0, tables = 0; FILE *file = fopen(MEMFILE, "r"); if (file == NULL) { fprintf(stderr, "Failed to open file %s\n", MEMFILE); return -1; } while (fgets(buf, 1024, file)) { get_word(buf, 0, word); if (!strcmp(word, "MemFree:")) { free = str_to_dec(buf, 0); } else if (!strcmp(word, "Buffers:")) { buffered = str_to_dec(buf, 0); } else if (!strcmp(word, "Cached:")) { cache = str_to_dec(buf, 0); } else if (!strcmp(word, "Active:")) { active = str_to_dec(buf, 0); } else if (!strcmp(word, "Inactive:")) { inactive = str_to_dec(buf, 0); } else if (!strcmp(word, "SwapFree:")) { swapfree = str_to_dec(buf, 0); } else if (!strcmp(word, "AnonPages:")) { anon = str_to_dec(buf, 0); } else if (!strcmp(word, "Slab:")) { slab = str_to_dec(buf, 0); } else if (!strcmp(word, "PageTables:")) { tables = str_to_dec(buf, 0); } } fclose(file); sprintf(data, "%f:%f:%f:%f:%f:%f:%f:%f:%f", free / 1024.0, buffered / 1024.0, cache / 1024.0, active / 1024.0, inactive / 1024.0, swapfree / 1024.0, anon / 1024.0, slab / 1024.0, tables / 1024.0); return 0; } int cpu_mem_parser(char *data) { char cpu[1024], mem[1024]; cpu_parser(cpu); mem_parser(mem); sprintf(data, "%s:%s", cpu, mem); return 0; }