On Wednesday 01 October 2003 07:06 pm, [EMAIL PROTECTED] wrote:
> Hi,
>
> In order to get an email advising me that a process is using too much %cpu,
> i wanted to be able to redirect the output of the Unix top command into a
> text file, then use regular expressions to get the data i need.
> However, redirecting top's output into a file, ends up being one long line
> with a lot of control-M characters and other funny characters like these:
Another way is to call top in batch mode (-b). This tells top to not send any
fancy control characters. If you want to catch just one iteration though,
you should also pass it "-n1" so that it doesn't just scroll screenfulls of
top information on your terminal.
Attached is a little quickie program I wrote to watch various aspects of top's
output over time. It might help to show how one could process top data.
--
/* Michael A. Nachbaur <[EMAIL PROTECTED]>
* http://nachbaur.com/pgpkey.asc
*/
"He expanded his chest to make it totally clear that here
was the sort of man you only dared to cross if you had a
team of Sherpas with you. "
#!/usr/bin/perl
use strict;
use warnings;
use Time::HiRes qw ( time sleep );
{
my $sleep_interval = shift @ARGV || 1;
my $max_loops = shift @ARGV || -1;
while ($max_loops-- != 0) {
open INSTATS, 'top -b -n1 |'
or die "I can't open top in batch mode\n";
[EMAIL PROTECTED] perftest]$ top -b -n1
#top - 14:58:20 up 30 days, 2:14, 43 users, load average: 2.91, 2.93, 2.90
#Tasks: 104 total, 4 running, 98 sleeping, 1 stopped, 1 zombie
#Cpu0 : 4.4% user, 27.5% system, 67.8% nice, 0.3% idle
#Cpu1 : 4.8% user, 26.0% system, 69.0% nice, 0.2% idle
#Mem: 3616768k total, 2553312k used, 1063456k free, 225360k buffers
#Swap: 2097136k total, 4948k used, 2092188k free, 2028244k cached
my %data = ();
while (my $line = ) {
if ($line =~ /load average:\s+(.*?), (.*?), (.*)/) {
$data{loadavg} = [$1, $2, $3];
}
if ($line =~ /Tasks:\s+(\d+) total,\s+(\d+) running,\s+(\d+) sleeping,\s+(\d+) stopped,\s+(\d+) zombie/) {
$data{tasks} = {
total=> $1,
running => $2,
sleeping => $3,
stopped => $4,
zombie => $5,
};
}
if ($line =~ /Cpu(\d?).*:\s+(.*?)\% user,\s+(.*?)\% system,\s+(.*?)\% nice,\s+(.*?)\% idle/) {
$data{"cpu$1"} = {
'user' => $2,
'system' => $3,
'nice' => $4,
'idle' => $5,
};
}
if ($line =~ /Mem:\s+(.*?)k total,\s+(.*?)k used,\s+(.*?)k free,\s+(.*?)k buffers/) {
$data{mem}->{total} = $1;
$data{mem}->{used}= $2;
$data{mem}->{free}= $3;
$data{mem}->{buffers} = $4;
}
if ($line =~ /Swap:\s+(.*?)k total,\s+(.*?)k used,\s+(.*?)k free,\s+(.*?)k cached/) {
$data{swap}->{total} = $1;
$data{swap}->{used} = $2;
$data{swap}->{free} = $3;
$data{mem}->{cached} = $4;
}
}
close INSTATS;
print time . "\t";
print "avg: (" . join(", ", @{$data{loadavg}}) . ")\t";
print "proc: (" . join("/", $data{tasks}->{running}, $data{tasks}->{total}) . ")\t";
print "mem: (" . join("/", $data{mem}->{used} - $data{mem}->{cached}, $data{mem}->{total}) . ")\n";
sleep($sleep_interval);
}
}