Tuesday, June 27, 2006

Followup: Checking for a process running

After some very helpful feedback and further work on my own, I'd like to post an improvement to the previous entry "Checking for a process running".

The idea is to get a list of PIDs of an executable Xyz, or other string of interest, suitable for passing to xargs kill.

First, the code.


#!/bin/sh
# Try to guess which ps command we have, ps -f or ps uxww
# Some ps programs accept both uxww and -f, but we prefer uxww.
if ps uxww > /dev/null 2>&1 ; then
PSOPTS=uxww
else
PSOPTS=-f
fi
ps -u $USER $PSOPTS | grep [X]yz | awk '{print $2}'

Now, the explanations. Except for #1, these suggestions are from Todd Eigenschink.

1. It's a script, not a one-liner. In my environment I needed to use the command on multiple platforms, and there are two different versions of the ps command on the different platforms. So a script is needed to detect which one is used so the right arguments can be passed. If you know which ps form you need, you can reduce this to a one-liner and perhaps make it an alias.

2. The -u option is supported by both flavors of ps and eliminates a separate grep call to filter out my processes. Actually, even the -u is probably unnecessary as I think ps emits only your own processes by default.

3. The [X]yz pattern is a sneaky way to eliminate the need for a separate grep to filter out the grep process itself. The pattern [X]yz matches Xyz, but now the grep process won't have Xyz in its ps entry, and thus won't include its own process in the output.

4. The awk fragment to extract the PID field from the ps output eliminates the need for the sed and cut commands I posted earlier.

No comments: