From 11c97887ef28e9b073d9abf1c2da70cd01491c9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=AB=8F=E8=A8=AA=E5=AD=90?= Date: Tue, 18 Jun 2024 00:16:45 +0900 Subject: =?UTF-8?q?=E3=83=A1=E3=83=A2=E3=83=AA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/memory.c | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/memory.c (limited to 'src/memory.c') diff --git a/src/memory.c b/src/memory.c new file mode 100644 index 0000000..833fa97 --- /dev/null +++ b/src/memory.c @@ -0,0 +1,52 @@ +#include "memory.h" + +#include +#include +#include + +long long int run_mem_command(const char *command) { + char buf[128]; + long long int res = 0; + + FILE *p = popen(command, "r"); + if (!p) { + fprintf(stderr, "ホストコマンドを実効に失敗: %s", command); + return 0; + } + + while (fgets(buf, sizeof(buf), p) != NULL) { + buf[strcspn(buf, "\n")] = '\0'; + } + + res = atoll(buf); + pclose(p); + + return res; +} + +void display_memory() { + long long int memused = 0; + long long int memtotal = 0; +#if defined(__OpenBSD__) + memused = run_mem_command("vmstat | awk 'END {printf $3}' | sed 's/M//'"); + memtotal = run_mem_command("sysctl -n hw.physmem") / 1024LL / 1024LL; +#elif defined(__FreeBSD__) || defined(__DragonFly__) + memtotal = run_mem_command("sysctl -n hw.physmem") / 1024LL / 1024LL; +#elif defined(__NetBSD__) + memused = run_mem_command("top | grep \"Memory:\" | awk '{print $2}' | " + "sed 's/M//'"); + memtotal = run_mem_command("sysctl -n hw.physmem64") / 1024LL / 1024LL; +#elif defined(__minix) + memtotal = run_mem_command("sysctl -n hw.physmem") / 1024LL / 1024LL; +#elif defined(__linux__) + long long int memaval = run_mem_command("cat /proc/meminfo | grep MemAvailable | " + "awk '{print $2}'") / 1024LL; + memtotal = run_mem_command("cat /proc/meminfo | grep MemTotal | " + "awk '{print $2}'") / 1024LL; + memused = memtotal - memaval; + /* memused = run_mem_command("cat /proc/meminfo | grep MemFree | " + "awk '{print $2}'") / 1024LL; */ +#endif + + printf("%lld MiB / %lld MiB", memused, memtotal); +} -- cgit v1.2.3