Image

Imageevilrabbit wrote in Imagelinux

Now I know technically speaking most linux distro's come with a "killall" script that will kill a process by name, not by PID. However for us who use the BSD machines, its not shipped with the os. At either rate, I ran across a perl script last night that does in fact let you kill pid's by name.

at either rate, this is the code, I wish I had it all in front of me to give the guy credit for coding it, but I will update you later with who the guy was for proper like respect.

on with the show?


my $psbinary="/bin/ps";
my $psargs="cax -o pid,command";
my $signal=15; # default TERM
my $cmd=$psbinary . ' ' . $psargs;
my @names;
my $report='';

$pid='';
$name='';

for(@ARGV) {
if (/^-(\d+)/) { $signal=$1; }
push @names,$_;
}
if (@names == 0) {
print STDERR "usage [-SIGNUM] processname ..\n";
exit 1;
}
open(PS,"$cmd |") || die "Can not run ps binary";
while() {
($pid,$name)=(/\s*(\d+)\s+([^\s]+).*/);
next if !$pid; # odd check.. it should never happen actually
next if !$name;
($name)=($name=~/.*\/([^\s]+)/) if ($name=~/.*\//);
chomp($name); # making sure it doesn't end with eol
for (@names) {
$report=$pid . ' ' if $name eq $_;
kill $signal,$pid if $name eq $_;
}
}
close(PS);
if ($report ne "") {
print "killed: $report\n";
} else {
print "no processes killed\n";
}