I'm trying to get the most accurate number I can for the total amount of memory being utilized by any process. My approach is to print all of the lines of /proc/PID/maps, find the difference of the two mem addresses supplied and add that number to a totalMem variable. As an example, here's one line from the /proc/PID/maps file:
7f00a05c9000-7f00a05cc000 rw-p 00000000 00:00 0
I have some C code (shown below) to get the difference and add it to the total.
The proc I'm working with is firefox, and the problem is, the total mem comes out to:
13050814464 bytes
which even I know isn't correct.
My C code to handle the mem address difference is:
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;}
And while I'm not too confident in my C, I'm thinking it's more of a source problem.
Some of my conclusions as to why the number is so big:
The kernel might be rounding the mem addresses up to accomadate page size, which makes sense as my page size is 4kb and the majority of my mem address differences are 4kb. This could mean the actually mem being used could be smaller.
I'm not accounting for deleted segments of memory which are displayed in the /proc/PID/maps file like so:
7f009120f000-7f0091210000 rw-s 00000000 00:01 2096 /memfd:mozilla-ipc (deleted)
I'm assuming I should subtract these from the total
If anyone has any other ideas as to how to get the most accurate reading for total mem usage of a proc (other than some builtin), please share!