【问题标题】:How to grab total physical memory from Kernel如何从内核中获取总物理内存
【发布时间】:2014-05-05 16:08:32
【问题描述】:

我正在使用linux/mm.h

struct sysinfo mem_info;

那么totalMemory = mem_info.totalram;

这让我知道我的设备有多少内存。现在,我如何获得正在使用的内存量?我真的很讨厌必须遍历每个正在运行的进程并计算正在使用的 ram 的总和。

【问题讨论】:

  • 如何在代码中使用它?
  • /usr/bin/top 的方式相同。只需将其作为文本读入并进行子字符串匹配即可。它专为这种用途而设计,因此在解析输入时不会出现令人讨厌的意外。

标签: c performance time linux-kernel kernel-module


【解决方案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

【讨论】:

  • 问题,该文件多久更新一次?我可能需要在 10 分钟的时间内运行您发布的几次代码。
  • 这不是一个真实的文件。当read 系统调用到达内核时,内核将调用必要的 API 调用并将结果格式化为文本(因此在读取时信息将“高达一微秒”)。您只需要确保它没有被 libc 或其他用户空间库缓冲。
猜你喜欢
  • 2020-07-07
  • 2017-04-26
  • 2010-12-05
  • 2021-05-02
  • 1970-01-01
  • 2015-05-28
  • 2011-12-15
  • 2021-07-20
相关资源
最近更新 更多