2017-04-18 45 views
-1
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显示不同的值。总RAM大小linux sysinfo vs/proc/meminfo

cat /proc/meminfo | grep MemTotal 
MemTotal:  16255004 kB 

他们为什么不同?在Linux中获得物理内存大小的正确方法是什么?

回答

2

这是由于溢出。当超过4十亿(如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