views:

1317

answers:

2

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.

+3  A: 
AlexKR
Thanks Alex, this is exactly what I wanted. Actually, the library reads /proc/* data, which is the way I would try it :)
minjang
Then mark the answer as accepted and upvote it.
Amir Afghani
+2  A: 

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.

Mr.Ree
Thanks for detailed answers. "PeakWorkingSetSize" is defined in Windows system, and it is similar to max rss as you pointed out.As you mentioned, libstatgrab reads file in /proc/$PID/status. The library also provides system-wide free memory by reading "/proc/meminfo" section.Thanks!
minjang