C 程序总结任何过程的总内存使用情况

问题描述 投票:0回答:1

我正在尝试获取任何进程使用的内存总量的最准确数字。我的方法是打印 /proc/PID/maps 的所有行,找到提供的两个内存地址的差异,并将该数字添加到totalMem 变量中。作为示例,以下是 /proc/PID/maps 文件中的一行:

7f00a05c9000-7f00a05cc000 rw-p 00000000 00:00 0

我有一些 C 代码(如下所示)来获取差异并将其添加到总数中。

我正在使用的程序是firefox,问题是,总内存为:

13050814464 bytes

连我都知道这是不正确的。

我处理内存地址差异的 C 代码是:

while ( (read = getline(&line, &len, fd_MapsFile) != -1) ) {
    char *space = strchr(line, ' ');
 
    if (space == NULL) {
        printf("invalid input string\n");
    }
 
    size_t len = space - line;
 
    char address[50];
 
    strncpy(address, line, len);
    address[len] = '\0';
 
    char address1[20];
    char address2[20];
 
    char *hyphen = strchr(address, '-');
 
    if (hyphen == NULL ) {
        printf("no hyphen found");
    }
                                                                                                                                                                          
    size_t address1len = hyphen - address;
    strncpy(address1, address, address1len);
    address1[address1len] = '\0';
 
    size_t address2len = strlen(address) - address1len - 1;
    strncpy(address2, hyphen+1, address2len);
    address2[address2len] = '\0';
 
    unsigned long addr1 = strtoul(address1, NULL, 16);
    unsigned long addr2 = strtoul(address2, NULL, 16);
    unsigned long difference = addr2 - addr1;
 
    printf("difference: %lu\n", difference);
 
    totalMem = totalMem + difference;
}

虽然我对我的 C 不太有信心,但我认为这更多是一个源问题。

我关于为什么这个数字如此之大的一些结论:

内核可能会将内存地址四舍五入到适应的页面大小,这是有道理的,因为我的页面大小是 4kb,而我的大部分内存地址差异都是 4kb。这可能意味着实际使用的内存可能会更小。

我没有考虑 /proc/PID/maps 文件中显示的已删除内存段,如下所示:

7f009120f000-7f0091210000 rw-s 00000000 00:01 2096                       /memfd:mozilla-ipc (deleted)

我假设我应该从总数中减去这些

如果有人对如何获得最准确的进程总内存使用情况(除了某些内置的)的读数有任何其他想法,请分享!

c
1个回答
0
投票

您想看:

/proc/PID/status`

其中,

VmSize:
就是您想要的。还有其他
Vm*:
字段也可能令人感兴趣,但
VmSize:
是所有字段的总数。

此值对应于

VSZ
为给定 PID 报告的
ps alx
字段

虽然您可能想自己在代码中阅读本文,但快速查找

firefox
将会是:

grep "Vmsize:" /proc/`pgrep firefox`/status

在我的系统上,我运行:

ps alx | egrep 'VSZ|firefox' | head -2
grep "VmSize:" /proc/`pgrep firefox`/status

输出:

F   UID     PID    PPID PRI  NI    VSZ   RSS WCHAN  STAT TTY        TIME COMMAND
0  1000 2784648       1  20   0 13148104 827588 x64_sy Sl tty1     15:12 /hdx/local/firefox/firefox-bin https://www.thunderbird.net/
VmSize: 13148104 kB
© www.soinside.com 2019 - 2024. All rights reserved.