5

我在 perl 中的 linux 机器上循环处理进程。我想显示特定进程的总 cpu,但我想显示进程的每个实例的总使用量。例如:

USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
northriv 10228  0.0  0.2  23692  8084 ?        S    Sep18   0:00 /usr/local/apache2/bin/httpd -k start
northriv 10229  0.0  0.2  23692  8084 ?        S    Sep18   0:00 /usr/local/apache2/bin/httpd -k start
northriv 10186  0.0  0.2  23692  8084 ?        S    Sep18   0:00 /usr/local/apache2/bin/httpd -k start
northriv 10187  0.0  0.2  23692  8084 ?        S    Sep18   0:00 /usr/local/apache2/bin/httpd -k start
speaktra 25535  0.2  1.0  46788 33212 ?        S    Sep23   6:04 /usr/local/apache2/bin/httpd -k start
speaktra 25547  0.2  0.8  40320 26712 ?        S    Sep23   6:21 /usr/local/apache2/bin/httpd -k start
wvneuroc  1570  0.2  0.0   2136  1044 ?        S    12:52   0:00 /usr/bin/qpopper -F -S
speaktra 25546  0.2  0.7  35680 22116 ?        S    Sep23   6:45 /usr/local/apache2/bin/httpd -k start
speaktra 1570  0.2  0.0   2136  1044 ?        S    12:52   0:00 /usr/bin/qpopper -F -S

然后这样的东西将由用户和这样的进程输出。

northriv
(0.0): /usr/local/apache2/bin/httpd

speacktra
(0.6): /usr/local/apache2/bin/httpd
(0.2): /usr/bin/qpopper -F -S

wvneuroc
(0.2): /usr/bin/qpopper -F -S

我知道我需要使用某种类型的哈希,但在那里不强,这是我目前使用的代码。

!/usr/bin/perl
use strict;
use warnings;

my @stats;
my $date=`date +"\%m-\%d-\%Y-\%r"`;
chomp $date;

my @process_table = `ps aux --sort=\%cpu|sed -e 's/\\s\\+/,/g'`;
for (@process_table)
{       chomp;
        $_ =~ s/        / /g;
        my ($user,$pid,$cpu,$mem,$cmd)=(split /,/,$_)[0,1,2,3,10];
        next if $user eq 'USER';
        if($cpu > 10)
        {
                push(@stats,"$user - WARNING(CPU:$cpu):\t$pid($cmd)\n");
        }
        if($cpu > 50)
        {
                push(@stats,"$user - CRITICAL(CPU:$cpu):\t$pid($cmd)\n");
        }
}
print $_ for @stats;
4

2 回答 2

4

您应该为此任务使用P9Y::ProcessTable模块。

于 2013-09-25T17:18:04.757 回答
2

我将%users哈希值添加到您的代码中。另请参阅:perldoc perldsc

use warnings;
use strict;

my @stats;
my $date=`date +"\%m-\%d-\%Y-\%r"`;
chomp $date;

my %users;
my @process_table = `ps aux --sort=\%cpu|sed -e 's/\\s\\+/,/g'`;
for (@process_table)
{       chomp;
        $_ =~ s/        / /g;
        my ($user,$pid,$cpu,$mem,$cmd)=(split /,/,$_)[0,1,2,3,10];
        next if $user eq 'USER';
        $users{$user}{$cmd} += $cpu;
        if($cpu > 10)
        {
                push(@stats,"$user - WARNING(CPU:$cpu):\t$pid($cmd)\n");
        }
        if($cpu > 50)
        {
                push(@stats,"$user - CRITICAL(CPU:$cpu):\t$pid($cmd)\n");
        }
}
print $_ for @stats;
for my $user (sort keys %users) {
    print "$user\n";
    print "($users{$user}{$_}): $_\n" for (sort keys %{ $users{$user} });
    print "\n";
}
于 2013-09-25T17:29:39.307 回答