解析 ps 进程命令的输出

问题描述 投票:0回答:2

我正在 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;
linux perl
2个回答
4
投票

您应该使用 P9Y::ProcessTable 模块来完成此任务。


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";
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.