我正在使用linux/mm.h
struct sysinfo mem_info;
然后totalMemory = mem_info.totalram;
这给了我设备有多少ram。现在,我如何获得正在使用的内存量?我真的很讨厌它必须经历每个运行过程并计算使用的ram总和。
答案 0 :(得分:1)
遵循常见Linux实用程序的最基本方法,即将/proc/meminfo
文件作为文本打开并解析它。
以下是busybox实施的示例:
/*
* Revert to manual parsing, which incidentally already has the
* sizes in kilobytes. This should be safe for both 2.4 and
* 2.6.
*/
fscanf(fp, "MemFree: %lu %s\n", &mfree, buf);
/*
* MemShared: is no longer present in 2.6. Report this as 0,
* to maintain consistent behavior with normal procps.
*/
if (fscanf(fp, "MemShared: %lu %s\n", &shared, buf) != 2)
shared = 0;
fscanf(fp, "Buffers: %lu %s\n", &buffers, buf);
fscanf(fp, "Cached: %lu %s\n", &cached, buf);
第535行:http://code.metager.de/source/xref/busybox/procps/top.c