Add Linux support, fix whitespace

Read /proc/meminfo, pull out some numbers and use them.
This commit is contained in:
Christian Barthel 2022-01-08 08:28:15 +01:00
parent a6e2ded980
commit 34c8e85e49
2 changed files with 232 additions and 120 deletions

View File

@ -1,2 +1,11 @@
# xmem(1) X11 Utility # xmem(1) X11 Utility
![fvwm and xmem](https://git.sdf.org/bch/xmem/raw/branch/master/www/xmem_fvwmbar.png) ![fvwm and xmem](https://git.sdf.org/bch/xmem/raw/branch/master/www/xmem_fvwmbar.png)
# Compile
```shell
# Linux with DEBUG:
CFLAGS=-DDEBUG make -f Makefile.linux
# BSD:
make
```

103
get_mem.c
View File

@ -244,3 +244,106 @@ void GetMemLoadPoint(Widget w, caddr_t closure, caddr_t call_data)
} }
#endif #endif
/* ------------------------------------------------------------------ */
#if __gnu_linux__
#include <X11/Xos.h>
#include <X11/Intrinsic.h>
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include "MemStripChart.h"
static unsigned int total_mem = 0;
int GetRamInKB(int type)
{
FILE *meminfo = fopen("/proc/meminfo", "r");
if(meminfo == NULL)
err(1, "fopen on /proc/meminfo failed: ");
char line[256];
int memory = -1;
int found = 0;
while(found == 0 && fgets(line, sizeof(line), meminfo))
{
if (type == 1) {
if((sscanf(line, "MemTotal: %d kB", &memory)) == 1)
found = 1;
}
if (type == 2) {
if(sscanf(line, "MemFree: %d kB", &memory) == 1)
found = 1;
}
if (type == 3) {
if(sscanf(line, "Buffers: %d kB", &memory) == 1)
found = 1;
}
if (type == 4) {
if(sscanf(line, "Cached: %d kB", &memory) == 1)
found = 1;
}
if (type == 5) {
if(sscanf(line, "SwapTotal: %d kB", &memory) == 1)
found = 1;
}
if (type == 6) {
if(sscanf(line, "SwapFree: %d kB", &memory) == 1)
found = 1;
}
}
if (!found)
warnx("failed to sscanf type %d", type);
fclose(meminfo);
return memory;
}
static void init_total_mem(void)
{
if (total_mem <= 0)
total_mem = GetRamInKB(1);
#ifdef DEBUG
printf("MemTotal: %d\n", total_mem);
#endif
}
void GetMemLoadPoint(Widget w, caddr_t closure, caddr_t call_data)
{
MemStripChartCallbackData ret;
init_total_mem();
/* free(1):
* total
* used = total - free - buffers - cache
* /proc/meminfo
* total = MemTotal
* code = total - free - buffers - cache (used)
* buffer = Buffers
* cached = Cached
* free = MemFree
*/
int mem_free = GetRamInKB(2);
int buffers = GetRamInKB(3);
int cached = GetRamInKB(4);
int swap_total = GetRamInKB(5);
int swap_free = GetRamInKB(6);
ret.code = (total_mem - mem_free - buffers - cached)/(float)total_mem;
ret.buffer = (buffers)/(float)total_mem;
ret.cached = (cached)/(float)total_mem;
ret.free = (mem_free)/(float)total_mem;
ret.swap = (swap_total - swap_free)/(float)swap_total;
#ifdef DEBUG
printf("%u %lf %lf %lf %lf\n", total_mem,
ret.code, ret.cached, ret.free, ret.swap);
#endif
memcpy(call_data, &ret, sizeof(MemStripChartCallbackData));
}
#endif