How do I check if a pid is running?

Michael Hudson mwh at python.net
Fri May 10 05:28:05 EDT 2002


"Noah" <noah at noah.org> writes:

> If I have the pid to a process under UNIX then how do I get the status of that pid?
> Specifically, I would like to see if child is running or not.
> If the pid cannot even be found then I will assume that 
> process is not running.
> 
> Note, that I think waitpid() may do what I want, but I'm not
> quite sure of the semantics. I do not want to wait for completion 
> of a child process, so I probably need WNOHANG option, but that
> returns 0 if the status is not immediately available, so presumably
> the process could still be running. Therefore a 0 value is ambiguous.
> 
> What do I need to do just to check if the pid even exists or not?

If you know that the process is yours (or you're running as root) you
can send signal 0 to it, e.g.

os.kill(the_pid, 0)

You'll get an exception (an OSError, I guess... yep) if you can't
signal the process.

In fact you can use the .errno attribute of said OSError and the errno
module to find out if it failed because the process doesn't exist or
because you don't have permissions to signal it:

>>> def pid_exists(pid):
...     try:
...         os.kill(pid, 0)
...         return 1
...     except OSError, err:
...         return err.errno == errno.EPERM
... 
>>> pid_exists(1)
1
>>> pid_exists(os.getpid())
1
>>> pid_exists(777)
0
>>> 

There may be better ways than this...

Cheers,
M.

-- 
  > With Python you can start a thread, but you can't stop it.  Sorry.
  > You'll have to wait until reaches the end of execution.
  So, just the same as c.l.py, then?
                       -- Cliff Wells & Steve Holden, comp.lang.python



More information about the Python-list mailing list