One problem is that the command line that invokes the script has the name of the process which you then query, by design; so one thing found will be the script itself.
This can be guarded against, but why go out to the system with that big pipeline?
Query the process in Perl, for example with Proc::ProcessTable
use warnings;
use strict;
use Proc::ProcessTable;
my $proc_name = shift // die "Usage: $0 process-name\n"; #/
my $pid;
my $pt = Proc::ProcessTable->new();
foreach my $proc (@{$pt->table}) {
next if $proc->cmndline =~ /$0.*$proc_name/; # not this script
if ($proc->cmndline =~ /\Q$proc_name/) {
$pid = $proc->pid;
last;
}
}
die "Not found process with '$proc_name' in its name\n" if not defined $pid;
kill 9, $pid; # must it be 9 (SIGKILL)?
my $gone_pid = waitpid $pid, 0; # then check that it's gone
Note that it is far nicer to "kill" a process by sending it SIGTERM
(usually 15), not SIGKILL
.
Looking for a process "name" can be perilous as there are many processes with long command lines running on a modern system that may contain that word. The code uses your requirement, to simply query by submitted name, but I recommend strengthening that with additional checks.
For many process details that the module can query see its stub module.
Even if you'd rather parse the process table yourself I would get only ps -ef
and then parse it in the script. That gives far more flexibility in ensuring that you really terminate what you want.