The memory usage of a process can be displayed by running:
$ ps -C processname -o size
SIZE
3808
Is there any way to retrieve this information without executing ps
(or any external program), or reading /proc
?
The memory usage of a process can be displayed by running:
$ ps -C processname -o size
SIZE
3808
Is there any way to retrieve this information without executing ps
(or any external program), or reading /proc
?
On a Linux system, a process' memory usage can be queried by reading /proc/[pid]/statm
. Where [pid]
is the PID of the process. If a process wants to query its own data, it can do so by reading /proc/self/statm
instead. man 5 proc
says:
/proc/[pid]/statm
Provides information about memory usage, measured in pages. The columns are: size total program size (same as VmSize in /proc/[pid]/status) resident resident set size (same as VmRSS in /proc/[pid]/status) share shared pages (from shared mappings) text text (code) lib library (unused in Linux 2.6) data data + stack dt dirty pages (unused in Linux 2.6)
You could just open the file with: fopen("/proc/self/statm", "r")
and read the contents.
Since the file returns results in 'pages', you will want to find the page size also. getpagesize ()
returns the size of a page, in bytes.
You have a few options to do find the memory usage of a program:
ps
, top
, or pmap
as you would from the command lineps
into your app and use it directly (it's open source, of course!)/proc
system (which is all that ps
does, anyways...)/proc
filesystem is just a view into the kernel's internal data structures, so this is really already done for you.The former are all educational from a system administration perspective, and would be the best options in a real-life situation, but the last bullet point is probably the most interesting. You'd probably want to read the source of Valgrind or memprof to see how it works, but essentially what you'd need to do is insert your mechanism between the app and the kernel, and intercept any requests for memory allocation. Additionally, when the process started, you would want to initialize its memory space with a preset value like 0xDEADBEEF. Then, after the process finished, you could read through the memory space and count the occurrences of words other than your preset value, giving you an estimate of memory usage.
Of course, things are always more complicated than they seem. What about memory used by shared libraries? Pipes? Shared memory between your processes and another? System calls? Virtual memory allocated but not used? Data buffered to the disk? There's a lot of calls to be made beyond your question 'memory of process', see this post for some additional concerns.