C / C ++ Usage API on Linux / Windows

I would like to receive information about memory usage both for the process and for the whole system. On Windows, this is pretty easy. GetProcessMemoryInfo and GlobalMemoryStatusEx make these tasks very, very easy. For example, GetProcessMemoryInfo gives the "PeakWorkingSetSize" of this process. GlobalMemoryStatusEx returns system available memory.

However, I need to do this on Linux. I am trying to find Linux system APIs that are equivalent to GetProcessMemoryInfo and GlobalMemoryStatusEx.

I found "getrusage". However, max 'ru_maxrss' (resident set size) in struct rusage is zero, which is not implemented. In addition, I have no idea to get free system memory.

The current workaround for it, I use "system (" ps -p% my_pid -o vsz, rsz ");". Manual registration to a file. But it is dirty and not convenient to process data.

I would like to know some fancy Linux APIs for this purpose.

+4
c memory-management linux winapi
Nov 04 '09 at 15:45
source share
2 answers

You can see how this is done in libstatgrab .
And you can also use it (GPL)

+6
Nov 04 '09 at 16:04
source share

Linux has a (modular) file system interface for extracting such data from the kernel, so it can be used in almost any language or scripting tool.

Memory can be complicated. There the program executable itself, presumably mmap () 'ed in. Shared libraries Using the stack. Using heap. Parts of software located in RAM. The portions have changed. Etc.




What is PeakWorkingSetSize? This sounds like the maximum resident set size (the maximum raw RAM with physical memory used by the process).

Although this can also be the total amount of virtual memory of the entire process (the sum for the parts in RAM and SWAPPED-out).




To no avail, on Linux, you can strace a process to see its kernel-level interactions. "ps" gets its data from the files / proc / $ {PID} / *.

I suggest you cat / proc / $ {PID} / status . The Vm * lines are quite useful.

In particular: VmData refers to the use of a process heap. VmStk refers to the use of the process stack.

If you continue to use "ps", you can consider popen () .




I have no idea to get the free memory of the whole system.

Always / usr / bin / free

Please note that Linux will use unused memory for file buffering and caching ... Thus, the line is +/- buffers / cache .

+5
Nov 05 '09 at 3:18
source share



All Articles