Linux でのメモリの空き容量の取得
C++ のコードで Linux 環境でのメモリの使用状況 を知りたくなった.
コマンドでは free などがあるが,それと同等のものを取得する関数.
Iwao@DS116:~/gcc_test/Test/t_linux/T_mem/t_mem$ free -h
total used free shared buff/cache available
Mem: 1.0G 695M 29M 49M 281M 162M
Swap: 2.0G 1.0G 1.0G
Iwao@DS116:~/gcc_test/Test/t_linux/T_mem/t_mem$ cat /proc/meminfo
MemTotal: 1030632 kB
MemFree: 16720 kB
Buffers: 9392 kB
Cached: 203592 kB
SwapCached: 227532 kB
Active: 393336 kB
Inactive: 489268 kB
Active(anon): 322836 kB
Inactive(anon): 397436 kB
Active(file): 70500 kB
Inactive(file): 91832 kB
Unevictable: 1408 kB
Mlocked: 1408 kB
SwapTotal: 2097148 kB
SwapFree: 1060108 kB
Dirty: 200 kB
Writeback: 0 kB
AnonPages: 538800 kB
Mapped: 71992 kB
Shmem: 50524 kB
Slab: 89312 kB
SReclaimable: 17608 kB
SUnreclaim: 71704 kB
KernelStack: 4368 kB
PageTables: 14768 kB
NFS_Unstable: 0 kB
Bounce: 0 kB
WritebackTmp: 0 kB
CommitLimit: 2612464 kB
Committed_AS: 4943664 kB
VmallocTotal: 1039360 kB
VmallocUsed: 6916 kB
VmallocChunk: 961204 kB
Iwao@DS116:~/gcc_test/Test/t_linux/T_mem/t_mem$ ./a.out
16474112
1055367168
Iwao@DS116:~/gcc_test/Test/t_linux/T_mem/t_mem$ cat main.cpp
#include <iostream>
#include <sys/sysinfo.h>
int main ()
{
{
struct sysinfo meminfo ;
::sysinfo(&meminfo);
std::cout << meminfo.freeram << std::endl;
std::cout << meminfo.totalram << std::endl;
}
return 0;
}
Iwao@DS116:~/gcc_test/Test/t_linux/T_mem/t_mem$
最初 getrusage を見つけたが,マニュアルにある様にこの目的では使えない.値は 0 で返ってくる.
次に見つけたのが sysinfo .
Fedora や Raspberry Pi ,Synology NAS で動作することを確認.
- meminfo {...} sysinfo uptime 17198 __kernel_long_t - loads __kernel_ulong_t [3] [0] 35520 __kernel_ulong_t [1] 30240 __kernel_ulong_t [2] 26880 __kernel_ulong_t totalram 2078154752 __kernel_ulong_t freeram 107687936 __kernel_ulong_t sharedram 19849216 __kernel_ulong_t bufferram 145534976 __kernel_ulong_t totalswap 2227171328 __kernel_ulong_t freeswap 2206625792 __kernel_ulong_t procs 468 __u16 pad 0 __u16 totalhigh 0 __kernel_ulong_t freehigh 0 __kernel_ulong_t mem_unit 1 __u32 _f char [0]