in reply to Determining a Unix PID

If you only need to make the determination once, then the answers above are good.

If you need to repeat the test, for instance, if you need to keep testing until the process has terminated, then you can save repeating the search process (by whatever method) more than once by retaining the PID from the first search and then use the trick described in perlfunc:kill.

If SIGNAL is zero, no signal is sent to the process. This is a useful way to check that the process is alive and hasn't changed its UID. See the perlport manpage for notes on the portability of this construct.

Ie. Once you know the process id

if( kill 0, $pid ) { # the process is still running } else { # has gone away. }

Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller

Replies are listed 'Best First'.
Re: Re: Determining a Unix PID
by skyknight (Hermit) on Jul 25, 2003 at 15:17 UTC

    The Camel Book, edition 3, page 735: "A SIGNAL of 0 tests whether a process is still alive and that you still have permission to signal it. No signal is sent. This way you can check whether the process is still alive and hasn't changed it's UID."

    If you want to lose the assumption about UID, but add the assumption that you're working on a system with a proc file system, you could instead do the following...

    $path = "/proc/$pid"; print "process $pid ", -e $path ? "is " : "is not ", "running\n"

    This may or may not be faster, depending on how much "system-callage" the various tests engender, and the relevance of that depends on whether this is a monitoring daemon firing off all fast and furious, or if it's a command line executed script that just does the test once.