Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ memory usage API in Linux/Windows

I'd like to obtain memory usage information for both per process and system wide. In Windows, it's pretty easy. GetProcessMemoryInfo and GlobalMemoryStatusEx do these jobs greatly and very easily. For example, GetProcessMemoryInfo gives "PeakWorkingSetSize" of the given process. GlobalMemoryStatusEx returns system wide available memory.

However, I need to do it on Linux. I'm trying to find Linux system APIs that are equivalent GetProcessMemoryInfo and GlobalMemoryStatusEx.

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

Current workaround for it, I'm using "system("ps -p %my_pid -o vsz,rsz");". Manually logging to the file. But, it's dirty and not convenient to process the data.

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

like image 816
minjang Avatar asked Nov 04 '09 15:11

minjang


2 Answers

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

like image 132
alexkr Avatar answered Sep 18 '22 18:09

alexkr


Linux has a (modular) filesystem-interface for fetching such data from the kernel, thus being usable by nearly any language or scripting tool.

Memory can be complex. There's the program executable itself, presumably mmap()'ed in. Shared libraries. Stack utilization. Heap utilization. Portions of the software resident in RAM. Portions swapped out. Etc.


What exactly is "PeakWorkingSetSize"? It sounds like the maximum resident set size (the maximum non-swapped physical-memory RAM used by the process).

Though it could also be the total virtual memory footprint of the entire process (sum of the in-RAM and SWAPPED-out parts).


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

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

Specifically: VmData refers to process heap utilization. VmStk refers to process stack utilization.

If you continue using "ps", you might consider popen().


I have no idea to get system-wide free memory.

There's always /usr/bin/free

Note that Linux will make use of unused memory for buffering files and caching... Thus the +/-buffers/cache line.

like image 39
Mr.Ree Avatar answered Sep 21 '22 18:09

Mr.Ree