#!/usr/bin/perl -w
#
# an SGI gmemusage(1)-like interface to the process table.
#
# Excluded processes
#
@ExcludedProcesses = ( "/proc/0" , "/proc/2" , "/proc/3" ) ;
%ProcSize = {} ;
%ProcRSS = {} ;
%nProc = {} ;
$TotProcs = 0 ;
$ls = "/bin/ls" ;
#
# Determine if a value is present in an array.
#
sub in
{
    $val = shift @_ ;
    foreach $i ( @_ )
    {
	return 1 if $val eq $i ;
    }
    return 0 ;
}
#
# Extract info about running processes.
#
sub GetInfo
{
    %ProcSize = {} ;
    %ProcRSS = {} ;
    $TotProcs = 0 ;
    %nProc = {} ;
    foreach $proc ( `$ls -d /proc/[0-9]*` )
    {
	chop $proc ;
	if ( in ( $proc , @ExcludedProcesses ) )
	{
	    next ;
	}
	$TotProcs++ ;
	open ( PROC , "$proc/status" ) or next ;
	while ( <PROC> )
	{
	    if ( /^Name:\s(.*)$/ )
	    {
		$ProcName = $1 ;
		# Do this to avoid unnecessary warnings from perl. can remove
		# later once we zap the -w .
		if ( ! defined $ProcSize { $ProcName } )
		{
		    $ProcSize { $ProcName } = $ProcRSS { $ProcName } = 0 ;
		}
	    }
	    if ( /^VmSize:\s*(.*)\s*kB/ )
	    {
		$ProcSize = $1 ;
	    }
	    if ( /^VmRSS:\s*(.*)\s*kB/ )
	    {
		$ProcRSS = $1 ;
	    }
	}
	close PROC ;
	$ProcSize { $ProcName } += $ProcSize ;
	$ProcRSS { $ProcName } += $ProcRSS ;
	$nProc { $ProcName }++ ;
    }
}
#
# Main()
#
while ( 1 )
{
    printf "%-20s%10s%10s%10s\n" , "Name" , "nProcs" , "totSize" , "totRSS" ;
    GetInfo ;
    foreach $i ( keys %nProc )
    {
	printf ( "%-20s%10d%10d%10d\n" , $i , $nProc { $i } ,
		$ProcSize { $i } , $ProcRSS { $i } ) ;
    }
    sleep 5 ;
}
exit 0 ;
