total ram size linux sysinfo vs /proc/meminfo

total ram size linux sysinfo vs /proc/meminfo

本文关键字:proc meminfo vs sysinfo ram size linux total      更新时间:2023-10-16
 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(的数字时,请确保使用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 %dn", before);
  printf("64bit intermediate calculations gives %dn", after);
  return 0;
}

编译并运行时:

$ gcc foo.c -o foo -m32 -Wall -Werror -ansi -pedantic && ./foo
32bit intermediate calculations gives 2994988
64bit intermediate calculations gives 61715244