【问题标题】:total ram size linux sysinfo vs /proc/meminfo总内存大小 linux sysinfo vs /proc/meminfo
【发布时间】:2017-09-14 20:13:47
【问题描述】:
 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 大小的正确方法是什么?

【问题讨论】:

    标签: c++ linux memory ram


    【解决方案1】:

    这是由于溢出。当涉及超过 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
    

    【讨论】:

      猜你喜欢
      • 2010-11-24
      • 1970-01-01
      • 2010-10-14
      • 1970-01-01
      • 2017-05-04
      • 2017-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多