geekt has asked for the wisdom of the Perl Monks concerning the following question:
I'd like to grab the percentage of memory/CPU that is being used by the user, and return it to two scalars for use in a script. I would think this would be a fairly common task, however Google has failed me. I was trying to wrap my head around the best regex to use on the results from `top -b -n 1 -u $username`, but decided to ask here first.
Edit: Sorry, I figured that posting extremely basic code when the main piece was the regex would be pointless, especially when I wasn't sure I was doing it the best way, but someone hit me with a book, so I'll post some basic example code.
Note: Code not guaranteed or likely to be error free.
#!/usr/bin/perl use strict; use warnings; my $memlimit = "25.0"; # maximum percentage of memory user can use my $cpulimit = "25.0"; # maximum percentage of CPU user can use my $username = `whoami`; my ($usermem, $usercpu) = getUserMemCPUperc( '$username' ); if (($usermem < $memlimit) && ($usercpu < $cpulimit)){ # do stuff! } else { # memory or CPU limits reached exit(0); } exit(0); sub getUserMemCPUperc { my( $username ) = shift; my $top = `top -b -n 1 -u $username`; # gets top from the system my ($cpu, $mem); $_ = $top; # @processes =~ /.../g; # regex to extract each process line # foreach my $process (@processes) { # my ($procpu, $procmem) =~ /.../; # get cpu and memory percent # $cpu += $procpu; # add process cpu percent to total # $mem += $procmem; # add process memory percent to total # } # return ($mem, $cpu); }
So, how would you do it?
Edit: Code that seems to work is posted below in reply. Originally trying to do research to figure out how to do this, I saw that top gave me exactly what I wanted, however this seems like a convoluted and inefficient method.
Edit: Proc::ProcessTable will not seem to work on my CentOS version, so I'll be working on improving the version posted below. Suggestions would be appreciated.
|
|---|