Friday, October 7, 2016

Perl script that checks memory usage of all perl scripts running on a linux machine.

This perl script checks the memory usage of all perl processes running on a linux machine (descending order of memory usage).

Practice Code/Not Very Efficient

#!/usr/bin/perl   

$result = `pidof perl`;
@lines = split ' ', $result;  
scalar @lines or die "No perl processes running at the moment\n"; 

$info;
$index=0; 
while(true){
 $query = "top -b -n 1"; 
 for($i=0;$i<20 && $index!=scalar(@lines);$index++,$i++){
  $query = $query." -p".$lines[$index];
 } 
 $result = `$query`; 
 $result =~ /.*COMMAND(.*)/ms; 
 $result = $1;
 $result =~ s/^\s+//;
 $result =~ s/\s?\Z//; 
 $info = $info.$result;
 if($index==scalar(@lines)){
  last;
 }
} 

@top_result = split '\n', $info; 
#print "No of processes : ".scalar @top_result."\n";
$max = 0; 
@lines2;
@names;

foreach $line (@top_result){
 if($line =~ /\s+(\S+)\s+$/){ 
  if($1 =~ /.*perl.*/){ 
   $line =~ m/(\d+) /;
   $pid = $1;
   if($pid != $$){
    push @lines2, $line;  
    $name = `cat /proc/$pid/cmdline`;   
    push @names, $name;
    if(length($name)>$max){$max = length($name);} 
   } 
  }else{
   push @lines2, $line; 
   $name = $1; 
   push @names, $name;
   if(length($name)>$max){$max=length($name);} 
  }
 } 
}
 
printf '-'x(87+2*$max)."\n";
printf "|%-${max}s | %5s | %7s | %2s | %2s | %6s | %5s | %5s | %1s | %4s | %4s | %8s | %${max}s|\n", "Script Name", "PID", "USER", "PR",
                "NI", "VIRT", "RES", "SHR", "S", "%CPU", "%MEM", "TIME+", "COMMAND";

printf '-'x(87+2*$max)."\n";

$index=0;
foreach $line (@lines2){
 $line =~ /(\S+)\s+\S+\s+\S+\s+$/;    
 $mem = $1; 
 $line = $line." ".$names[$index++];    
 if(!defined($structure{$mem})){
  $structure{$mem} = $line;
 }else{
  $structure{$mem} = $structure{$mem}."\n".$line; 
 } 
} 

@uze = reverse sort {$a <=> $b} keys %structure;  
 
$index=0;
foreach $key(@uze){  
 @op = split '\n', $structure{$key}; 
 foreach $consideration(@op){ 
  @splitt = split ' ', $consideration;
  printf "|%-${max}s | %5s | %7s | %2s | %2s | %6s | %5s | %5s | %1s | %4s | %4s | %8s | %${max}s|\n",
  $splitt[12], $splitt[0], $splitt[1], $splitt[2], $splitt[3], $splitt[4], $splitt[5], $splitt[6],
  $splitt[7], $splitt[8], $splitt[9], $splitt[10], $splitt[11];
  $structure{$splitt[9]} = [@$structure{$splitt[9]}, $line]; 
 }
}
printf '-'x(87+2*$max)."\n"; 


No comments:

Post a Comment