2

I looked around, and none of the solutions worked for me. I want to terminate a perl script using the command line.

For example:

killall myscript.pl

I'm looking for a solution similar to this, all help is appreciated. Thanks.

user3101398
  • 133
  • 1
  • 1
  • 5

2 Answers2

4

You can try pkill, which is a standard on most of today's distributions.

Eg.

pkill -f myscript.pl

If you want a more portable solution, then you can grep for the name, extract the PID, and kill:

kill $(ps xa | grep [m]yscript | awk '{ print $1; exit }')
janos
  • 120,954
  • 29
  • 226
  • 236
tvm
  • 3,263
  • 27
  • 37
  • I don't think that will work because `ps` will see `perl /my/path/myscript.pl` –  Dec 14 '13 at 16:40
  • Just tried this. Doesn't seem to be working. – user3101398 Dec 14 '13 at 16:44
  • You can always use the -f switch, i've edited the original answer. See http://stackoverflow.com/questions/8987037/how-to-kill-all-processes-with-a-given-partial-name – tvm Dec 14 '13 at 16:45
  • 1
    I would like to call out a subtle bit of unstated cleverness in @tvm's answer: `grep [m]yscript`. The square brackets are the clever bit. Having a character class that consists of a single character is functionally the same as if you left the brackets out, as far as the regex itself is concerned. BUT: without that, you would actually get *two* hits from `ps` - the one you want AND the call to grep itself. With the square brackets, the grep call doesn't match, because it has some *literal* square brackets, so it would match `\[m\]yscript`, but not `[m]yscript`. – Edward Dec 14 '13 at 19:21
2

In perl, assigning to the variable $0 should change the name of the process listing. This will affect the output of the ps command, on which killall and pkill rely.

killall myscript.pl won't work without the extra -f argument @tvm suggested because the script is running within another program (the perl interpreter) so the process will be listed as perl /path/to/myscript.pl

You could try pkill perl but that will kill all perl interpreters that the current user has permission to kill so it could be dangerous.

The best way to go about this programmatically is to modify the name of the process by assigning to the $0 variable

#!/usr/bin/perl
$0 = 'myscript';
sleep 60;

... and then in a standard unix shell:

$pkill -9 myscript

See Dynamically name processes for more info.

Community
  • 1
  • 1