Wednesday, January 17, 2007

Deciding whether a process is running

When I discovered "ps -p pid" would set the exit code to failure if pid wasn't found, I was happy. It seemed a much cleaner and more portable way to decide if a process was running, as opposed to grepping through ps output. However, it looks like the ps command on the Mac (MacOS 10.4) isn't setting the exit code in the case the process isn't found, so you get a false positive (process looks like it's running when it isn't):


% ps -p 2664
PID TT STAT TIME COMMAND
% echo $?
0
%

While I would like to use ps -p pid since it's a tight one-liner, this looks like I'm going to have to count how many lines of output ps -p has. Something like this:

test 2 -eq `ps -p $pid | wc -l | xargs expr`

The goal is a line (or lines, if absolutely necessary), which is foremost portable, i.e. works on any many platforms and as many variants of ps as possible.

Any comments or suggestions from the readers?

Edited Jan 23, 2007: Removed the "ps -p" and just left the test command.

2 comments:

Anonymous said...

pgrep is your friend here.

JFKBits said...

As helpful as pgrep may be, it's not available by default on Mac OS 10.4 :(

I have a lot of Unix variants that I run this script on and Mac is one of them.

So the challenge here is write a script served from a net-mounted directory that runs on as many platforms as possible that determines if a given process is still running.

There always seem be one more system-dependent wrinkle that messes up solutions that work well for people with less-demanding needs.