Created
May 5, 2009 15:20
-
-
Save antonlindstrom/107007 to your computer and use it in GitHub Desktop.
School assignment #7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
# | |
# Program for Process Management | |
# Require the neccesary modules. | |
use Proc::ProcessTable; | |
use POSIX qw/strftime floor ceil/; | |
# Initiate class Proc::ProcessTable. | |
$process = new Proc::ProcessTable; | |
# Open /etc/passwd to get user name and uid. | |
open(USR, "/etc/passwd") || die "/etc/passwd could not be accessed!\n $!\n"; | |
@users = <USR>; | |
foreach (@users) { | |
@usrposts = split(/:/, $_); | |
# Set user uid as key and username as value. | |
$user{$usrposts[2]} = $usrposts[0]; | |
} | |
# format printf and print header. | |
$FORMAT = "%-4s %-6s %-5s %-10s %s\n"; | |
printf($FORMAT, "PID", "USER", "CPU","TIME", "CMDLINE"); | |
# Print out every process over 0% | |
foreach $p( @{$process->table} ) { | |
if ($p->pctcpu > 0.00 ) { | |
$timeofprocess = time-$p->start; | |
# Time in minutes and seconds. | |
$timeformatted = int(($p->time/1000000)/60).":".int(($p->time/1000000)%60); | |
# Print PID, USER, CPU Percentage, TIME and CMDLINE. | |
printf ($FORMAT, $p->pid, $user{$p->uid}, (ceil($p->pctcpu)."%"), $timeformatted, $p->cmndline); | |
# If process has run more than 2 minutes, is owned by a standard user (over 1000 uid) and is using over 90% CPU. | |
if ( ($timeofprocess > 120) && ($p->uid >= 1000) && (ceil($p->pctcpu) >= 90) ) { | |
push(@ptokill,$p->pid); | |
} | |
} | |
} | |
print "\n"; | |
# Preforming killing output | |
foreach (@ptokill) { | |
# Kill if processid is in the array @ptokill. | |
foreach $pk( @{$process->table} ) { | |
next if ($pk->pid != $_); | |
print "Killing process $_ from owner $user{$pk->uid}\n"; | |
print " Command line: ".$pk->cmndline."\n"; | |
$pkillnow = $pk->pid; | |
#system("kill $pkillnow"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment