Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

From lack of a method to get the CPU usage states in percentage form from some linux command, I have turned to perl. What I'm trying to do is get perl to capture the results of top -s | grep "CPU states". A new line is displayed every six seconds or so. I've tried all the piping methods that I've seen but none of them seem to work. Any ideas why this isn't working?

Thanks!

Replies are listed 'Best First'.
Re: Piping top
by BazB (Priest) on Oct 28, 2002 at 23:39 UTC

    If you want to do this all in Perl, rather than resorting to system calls, try Proc::ProcessTable - it should give you the state of a process, and lots of other rather useful bits of information you'd expect from UNIX commands like top and ps.

    Here's a quick and dirty example to print the PID, state and commandline of all of the processes that are on CPU when the script runs (tested on Linux - IIRC on Solaris you should look for the phrase "On processor"):

    #!/usr/bin/perl use strict; use warnings; use Proc::ProcessTable; my $t = new Proc::ProcessTable; foreach my $proc (@{$t->table}) { if ($proc->state =~ /run/oi) { print join " ", $proc->pid, $proc->state, $proc->cmndline, "\n"; } }

    Cheers

    BazB

    Update: BTW, there are a number of methods that Proc::ProcessTable offers that will give you the amount of CPU time used by a process (and it's children if you want) and the like. Check the module's README.

Re: Piping top
by sauoq (Abbot) on Oct 28, 2002 at 22:49 UTC

    You should probably be using -b (batch mode) rather than -s (secure mode). That might be the problem.

    That aside though, have you tried vmstat(8)?

    -sauoq
    "My two cents aren't worth a dime.";
    
Re: Piping top
by toiletmonster (Novice) on Oct 29, 2002 at 18:36 UTC
    this works too.
    #!/usr/bin/perl -w use strict; use IPC::Open2; $|=1; open2( my $read, my $write, "top -b" ); while( <$read> ) { print if /CPU states/ ; }
    also if you try those piping methods again and wait for a really really long time (like 3 or 4 minutes) you will eventually get output. not sure what the deal is exactly there. guess the buffer isn't flushing? often? or something? for example, try top -b | grep "CPU states | less and wait for a while. it will eventually come up with some output.