以下程序是计算当前虚拟内存。
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
int parseLine(char* line){
// This assumes that a digit will be found and the line ends in " Kb".
int i = strlen(line);
const char* p = line;
while (*p <'0' || *p > '9') p++;
line[i-3] = '\0';
i = atoi(p);
return i;
}
int getValue(){ //Note: this value is in KB!
FILE* file = fopen("/proc/self/status", "r");
int result = -1;
char line[128];
while (fgets(line, 128, file) != NULL){
if (strncmp(line, "VmSize:", 7) == 0){
result = parseLine(line);
break;
}
}
fclose(file);
return result;
}
查询Linux系统下的进程内存信息,可打开文件/proc/self/status,如下:
Name: whatever
State: S (sleeping)
Tgid: 19340
Pid: 19340
PPid: 19115
TracerPid: 0
Uid: 0 0 0 0
Gid: 0 0 0 0
FDSize: 256
Groups: 0 1 2 3 4 6 10 11 20 26 27
VmPeak: 676252 kB
VmSize: 651352 kB
VmLck: 0 kB
VmHWM: 420300 kB
VmRSS: 420296 kB
VmData: 581028 kB
VmStk: 112 kB
VmExe: 11672 kB
VmLib: 76608 kB
VmPTE: 1244 kB
Threads: 77
SigQ: 0/36864
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: fffffffe7ffbfeff
SigIgn: 0000000010001000
SigCgt: 20000001800004fc
CapInh: 0000000000000000
CapPrm: 00000000ffffffff
CapEff: 00000000fffffeff
Cpus_allowed: 0f
Mems_allowed: 1
voluntary_ctxt_switches: 6518
nonvoluntary_ctxt_switches: 6598
VmPeak: 该进程峰值虚拟内存;
VmSize:整个进程的虚拟内存大小,是VMLib、VmExe、VMData和VmStk的总和;
VmLck:虚拟内存锁。进程当前使用的并且加锁的虚拟内存总数,锁住的内存不能交换到硬盘;
VmHWM:进程所占用物理内存的峰值;
VmRSS:进程现在使用的物理内存大小。
虚拟内存驻留集合大小,这是驻留在物理内存的一部分,他没有交换到硬盘,包含代码、数据和栈;
VmData:虚拟内存数据,堆使用的虚拟内存;
VmStk:虚拟内存栈,栈使用的虚拟内存;
VmExe:可执行的虚拟内存,可执行的静态链接库所使用的虚拟内存;
VmLib:虚拟内存库动态链接库所使用的虚拟内存。