Take the 2-minute tour ×

Is there a way to generically retrieve process stats using Perl or Python? We could keep it Linux specific.

There are a few problems: I won't know the PID ahead of time, but I can run the process in question from the script itself. For example, I'd have no problem doing:

./myscript.pl some/process/I/want/to/get/stats/for

Basically, I'd like to, at the very least, get the memory consumption of the process, but the more information I can get the better (like run time of the process, average CPU usage of the process, etc.)


share|improve this question
A similar question was asked by szagab a couple of weeks ago. –  innaM Apr 24 '09 at 13:29
add comment

3 Answers

up vote 7 down vote accepted

Have a look at the Proc::ProcessTable module which returns quite a bit of information on the processes in the system. Call the "fields" method to get a list of details that you can extract from each process.

I recently discovered the above module which has just about replaced the Process module that I had written when writing a Perl kill program for Linux. You can have a look at my script here.

It can be easily extended to extract further information from the ps command. For eg. the 'getbycmd' method returns a list of pid's whose command line invocation matches the passed argument. You can then retrieve a specific process' details by calling 'getdetail' by passing that PID to it like so,

my $psTable = Process->new();

# Get list of process owned by 'root'
for my $pid ( $psTable->getbyuser("root") ) {

    $psDetail = $psList->getdetail( $pid );
    # Do something with the psDetail..

share|improve this answer
add comment

A common misconception is that reading /proc is like reading /home. /proc is designed to give you the same information with one open() that 20 similar syscalls filling some structure could provide. Reading it does not pollute buffers, send innocent programs to paging hell or otherwise contribute to the death of kittens.

Accessing /proc/foo is just telling the kernel "give me information on foo that I can process in a language agnostic way"

If you need more details on what is in /proc/{pid}/ , update your question and I'll post them.

share|improve this answer
I have no problem reading proc/{pid}/. But once the child process terminates, proc/{pid}/ is gone, isn't it? How can I ensure it's there until I'm done? –  FreeMemory Apr 24 '09 at 13:35
I think I remember that holding an open filehandle to the /proc/pid/ directory keeps it from disappearing, but I'm not sure. If you're the parent, the /proc/pid/ directory will definitely stay around as long as you don't reap the child (custom $SIG{CHLD}). –  ephemient Apr 24 '09 at 15:48
add comment

If you are fork()ing the child, you will know it's PID.

From within the parent you can then parse the files in /proc/<PID/ to check the memory and CPU usage, albeit only for as long as the child process is running.

share|improve this answer
add comment

Your Answer


