c++ - 总 RAM 大小 linux sysinfo 与/proc/meminfo

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

最佳答案

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

相关文章:

Linux 32位反汇编有下一个字节的调用指令

linux - 用于 Linux 的图形 DIFF 程序

Java 销毁变量

java - 调用 hashSet.clear() 后创建一个新的 HashSet 还是重用更好

c++ - C/C++ 指针是保持绝对内存地址,还是相对于应用程序或相对于模块?

c++ - 在 C 中是否有一组标准的库用于动态字符串、列表和字典?

c++ - 使用#line 控件时调试器的奇怪行为

c++ - 在 C++ vs2015 中嵌入 python 3

python - 使用Python在Linux上的许多文件中查找并替换字符串

c++ - 使用 C++ 在 Arduino 上编写复杂的程序。如何正确使用对象或更好地使用普通 C?