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

Problem: All 12 processes are not being populated into hash.

Reason: unknown. Why dont I see the last 12 from tail -12?

use strict; use warnings; my (%prochash,@parray,@pids,$list,$pid,$time,$cpu,$user,$args); $|=1; push @parray, qx(/usr/bin/ps -ef -o pid,time,pcpu,user,args|/usr/bin/t +ail -12); print scalar @parray,"\n"; foreach (@parray) { $pid = (split)[0]; $time = (split)[1]; $cpu = (split)[2]; $user = (split)[3]; $args = (split)[4]; $prochash{$cpu} = { 'pid' => $pid, 'time' => $time, 'user' => $user, 'args' => $args, }; } use Data::Dumper; print Dumper \%prochash; __DATA__ 12 $VAR1 = { '0.1' => { 'pid' => '10485852', 'time' => '02:16:16', 'args' => '/opt/freeware/ossec/bin/ossec-syscheck +d', 'user' => 'root' }, '0.0' => { 'pid' => '14876814', 'time' => '00:00:00', 'args' => '/bin/bsh', 'user' => 'root' } };
Thank you!

Replies are listed 'Best First'.
Re: process table
by roboticus (Chancellor) on Dec 20, 2013 at 19:48 UTC

    teamassociated:

    Because you have two CPUs, and a hash holds one item. So the last one read wins for each CPU. Try this to get a hash of arrays (HoA):

    push @{$prochash{$cpu}}, { 'pid' => $pid, 'time' => $time, 'user' => $user, 'args' => $args, };

    Or if you want a hash of hashes (HoH), use the first level for the CPU and the second for the PID:

    $prochash{$cpu}{$pid} = { 'pid' => $pid, 'time' => $time, 'user' => $user, 'args' => $args, };

    There are other ways to do it, too. You may want to review perldoc perldsc

    Update: Changed language a little to clarify.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re: process table
by aitap (Curate) on Dec 20, 2013 at 19:49 UTC

    That's because you use the "%CPU" column as the hash key, yet its values are not unique, so newer values overwrite the older ones. For example, this is what I get on my machine:

    $ ps -ef -o pid,time,pcpu,user,args|/usr/bin/tail -12 | perl -MData::D +umper -ne'$_{(split)[2]}++;END{print Dumper \%_}' $VAR1 = { '0.4' => 1, '%CPU' => 1, '0.0' => 7 };
    Use the PID column instead.

    Update: was a bit outrun by roboticus (++).