views:

576

answers:

4

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.)

Thanks.

+2  A: 

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.

Alnitak
+2  A: 

A similar question was asked by szagab a couple of weeks ago.

innaM
+1  A: 

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.

Tim Post
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
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
+6  A: 

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..

}
muteW