Best way to determine if a certain PID is still running

Lars Gustäbel lars at gustaebel.de
Fri Feb 3 04:48:54 EST 2006


On Thu, Feb 02, 2006 at 05:10:24PM -0800, David Hirschfield wrote:
> I'm launching a process via an os.spawnvp(os.P_NOWAIT,...) call.
> So now I have the pid of the process, and I want a way to see if that 
> process is complete.
> 
> I don't want to block on os.waitpid(), I just want a quick way to see if 
> the process I started is finished. I could popen("ps -p %d" % pid) and 
> see whether it's there anymore...but since pids get reused, there's the 
> chance (however remote) that I'd get a false positive, plus I don't 
> really like the idea of calling something non-pure-python to find out.

You could try this:

import os, errno
try:
    os.kill(pid, 0)
except OSError, e:
    if e.errno == errno.ESRCH:
        # process has finished
        ...
else:
    # process exists
    ...

Unfortunately, this way cannot save you from getting false
positives with reused pids.

The IMO better way is to use the subprocess module that comes
with Python 2.4. How to replace os.spawn* calls is described
here: http://www.python.org/doc/2.4.2/lib/node244.html

-- 
Lars Gustäbel
lars at gustaebel.de

To a man with a hammer, everything looks like a nail.
(Mark Twain)



More information about the Python-list mailing list