dotfiles

personal configuration files and scripts
git clone https://tongong.net/git/dotfiles.git
Log | Files | Refs | README

mem.c (1264B)


      1 #include <stdio.h>
      2 
      3 #include "../util.h"
      4 #include "mem.h"
      5 
      6 #define ICON " "
      7 
      8 #define MEMFILE             "/proc/meminfo"
      9 #define MAX_CHARS_PER_LINE  40
     10 
     11 /* https://stackoverflow.com/a/4771386 */
     12 _Bool starts_with(const char *restrict string, const char *restrict prefix)
     13 {
     14     while(*prefix)
     15     {
     16         if(*prefix++ != *string++)
     17             return 0;
     18     }
     19     return 1;
     20 }
     21 
     22 size_t memu(char *str, int sigval)
     23 {
     24     /* usage = (memtotal - memavailable) / memtotal */
     25     unsigned int memavail = 0;
     26     unsigned int memtotal = 0;
     27     FILE *meminfo;
     28     char currline[MAX_CHARS_PER_LINE];
     29 
     30     /* read file line by line until MemAvailable and MemTotal are found or the
     31      * end is reached */
     32     meminfo = fopen(MEMFILE, "r");
     33     do {
     34         fgets(currline, MAX_CHARS_PER_LINE, meminfo);
     35 
     36         if (starts_with(currline, "MemTotal")) {
     37             sscanf(currline, "%*s %d %*s", &memtotal);
     38         }
     39 
     40         if (starts_with(currline, "MemAvailable")) {
     41             sscanf(currline, "%*s %d %*s", &memavail);
     42         }
     43 
     44     } while (!(feof(meminfo) || (memavail && memtotal)));
     45     fclose(meminfo);
     46 
     47     return SPRINTF(str, ICON "%03d%%", ((memtotal - memavail) * 100) / memtotal);
     48 }
     49 
     50 void memc(int button)
     51 {
     52     TERMCMD("htop", "-s", "PERCENT_MEM");
     53 }