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大小的正确方法是什么?
发布于 2017-04-18 20:34:25
这是溢出造成的。如果涉及的数字超过40亿(如4GB+内存),请确保使用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 61715244https://stackoverflow.com/questions/43481494
复制相似问题