总的RAM大小linux sysinfo vs / proc / meminfo

时间:2017-04-18 20:20:25

标签: c++ linux memory ram

 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大小的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

这是由于溢出造成的。当涉及超过40亿的数字(例如4GB + RAM)时,请确保使用64位+类型:

 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