struct sysinfo sys_info;
int32_t total_ram = 0;
if (sysinfo(&sys_info) != -1)
total_ram = (sys_info.totalram * sys_info.mem_unit)/1024;
上面代码中total_ram的值为3671864。但是/proc/meminfo显示了不同的值。
cat /proc/meminfo | grep MemTotal
MemTotal: 16255004 kB
为什么它们不同?在 Linux 中获取物理 RAM 大小的正确方法是什么?
最佳答案
这是由于溢出造成的。当涉及到超过 40 亿的数量(例如 4GB+ RAM)时,请确保使用 64bit+ 类型:
struct sysinfo sys_info;
int32_t total_ram = 0;
if (sysinfo(&sys_info) != -1)
total_ram = ((uint64_t) sys_info.totalram * sys_info.mem_unit)/1024;
这是一个独立的示例:
#include <stdint.h>
#include <stdio.h>
#include <sys/sysinfo.h>
int main() {
struct sysinfo sys_info;
int32_t before, after;
if (sysinfo(&sys_info) == -1) return 1;
before = (sys_info.totalram * sys_info.mem_unit)/1024;
after = ((uint64_t)sys_info.totalram * sys_info.mem_unit)/1024;
printf("32bit intermediate calculations gives %d\n", before);
printf("64bit intermediate calculations gives %d\n", after);
return 0;
}
编译并运行时:
$ gcc foo.c -o foo -m32 -Wall -Werror -ansi -pedantic && ./foo
32bit intermediate calculations gives 2994988
64bit intermediate calculations gives 61715244
关于c++ - 总 RAM 大小 linux sysinfo 与/proc/meminfo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43481494/