total ram size linux sysinfo vs /proc/meminfo
total ram size linux sysinfo vs /proc/meminfo
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
相关文章:
- 在 Linux 上没有 /proc/self/exe 的 C/C++ 运行时可执行文件的大小?
- Proc*C 应用程序在 Oracle 12.2 中崩溃
- 获取 inode 以便在 /proc/net/udp 中查找
- total ram size linux sysinfo vs /proc/meminfo
- 在 SAS 中使用带有 PROC PROTO 的 Linux c++ 库
- 在X64模式下从C /CLI调用MASM PROC会产生意外的性能问题
- 使用 C++ 解析 /proc/stat
- 查看/proc/self/状态时,VMRSS或VMIZE的变化不一致
- C++ Windows API - 如何使用ListView的默认WIndows Proc?
- 需要在 c++ 中从另一个文件调用 tcl proc
- 在Linux上的C 中列出了安装点,而无需使用 /proc /motts, /etc /fstab,system()
- 哪个线程调用windows proc回调函数
- 当可执行文件在执行过程中被替换时如何处理"/proc/self/exe"的readlink()?
- 带有 ProC 的预编译标头
- SigCgt 值未在 /proc/<pid>/status 文件中更新?
- 使用 fscanf 从 /proc C++读取
- Linux - 从 /proc/partitions 内容到我可以'ls'的内容
- Linux gcc:缺少"proc.h"标头。'proc'结构在哪里定义?
- /proc/fd文件描述符显示了什么
- 以特定用户身份运行proc com服务器