Calculating used memory by a set of processes on Linux

c, c++, linux, memory, posix

Solution

You will want to iterate through each processes `/proc/[pid]/smaps`

It will contain an entry for each VM mapping of the likes:

7ffffffe7000-7ffffffff000 rw-p 00000000 00:00 0                          [stack]
Size:                100 kB
Rss:                  20 kB
Pss:                  20 kB
Shared_Clean:          0 kB
Shared_Dirty:          0 kB
Private_Clean:         0 kB
Private_Dirty:        20 kB
Referenced:           20 kB
Anonymous:            20 kB
AnonHugePages:         0 kB
Swap:                  0 kB
KernelPageSize:        4 kB
MMUPageSize:           4 kB

`Private_Dirty` memory is what you are interested in.

If you have the `Pss` field in your `smaps` file then this is the amount of resident memory divided by the amount of processes that share the physical memory.

`Private_Clean` could be copy-on-write mappings. Those are commonly used for shared libraries and are generally read/no-write/execute.

Problem

I'm having trouble with calculating the actually used memory (resident) by a set of processes. The issue that just came up is a user with a set of processes that share memory between themselves, so a simple addition of used memory ends up with a nonsense number (>60gb when the machine only has 48gb memory). Is there any simple way to approach this problem? I can probably do some approximation. Take `(res mem - shared mem) * num proc + shared mem`. But not all processes necessarily share the same memory block. I'm looking for a POSIX or Linux solution to this problem for C/C++.

Original source