Wednesday, August 18, 2010

UNIX - handle Kill when no PID


I was grepping for a particular process say 'Sync' in my process listing

$ ps -ef | grep Sync
testuser 26057 1 0 06:21 ? 00:00:00 /opt/nms/ety_master Sync -c 10
testuser 26066 1 0 06:21 ? 00:00:00 /opt/nms/ety_master Sync -c 14
testuser 26067 1 0 06:21 ? 00:00:00 /opt/nms/ety_master Sync -c 22
testuser 26266 23299 0 06:21 pts/3 00:00:00 grep Sync

The 'grep' from the above listing can be removed by using a regular expression:

$ ps -ef | grep [S]ync
testuser 26057 1 0 06:21 ? 00:00:00 /opt/nms/ety_master Sync -c 10
testuser 26066 1 0 06:21 ? 00:00:00 /opt/nms/ety_master Sync -c 14
testuser 26067 1 0 06:21 ? 00:00:00 /opt/nms/ety_master Sync -c 22

I wrote a one liner which basically extracts the PIDs from the above output and then kill them.

$ kill -9 $(ps -ef | awk '/[S]ync/ {print $2}')

ps -ef | grep [S]ync
is same as
ps -ef | awk '/[S]ync/'

Now if there is no 'Sync' process running , the above command is going to throw a message like this:

kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]

To handle this, here is the solution:

$ ps -ef | awk '/[S]ync/ {print $2}' | xargs -r kill -9

From XARGS(1) man page:

--no-run-if-empty, -r
If the standard input does not contain any nonblanks, do not run the command.
Normally, the command is run once even if there is no input. This option is a GNU extension.

4 comments:

James said...

How about using pgrep/pkill?

Sanity check: ps -fP $(pgrep -f Sync)
Kill them: pkill -9 -f Sync

Jadu Saikia said...

@James, thanks a lot. Ya, as you mentioned pgrep and 'pkill -f' can be used as a replacement of this.

The problem I was facing in pkill was that my actual process was 'ety_master' and 'Sync' was a parameter to it. So 'pkill Sync' was not killing these processes. Also I cant issue pkill ety_master as there were other ety_master processes with other parameters. But from your comment I came to know about -f switch and is really helpful. Thanks again.

voyeg3r said...

try pkill command

pkill program

Mahesh Kharvi said...

ps -ef | awk '/[S]ync/{system("kill -9 "$2)}'

© Jadu Saikia www.UNIXCL.com