Portable way to tell if a process is still alive

Nobody nobody at nowhere.com
Wed Dec 30 13:28:32 EST 2009


On Tue, 29 Dec 2009 12:35:11 +0430, Laszlo Nagy wrote:

> Suppose we have a program that writes its process id into a pid file. 
> Usually the program deletes the pid file when it exists... But in some 
> cases (for example, killed with kill -9 or TerminateProcess) pid file is 
> left there. I would like to know if a process (given with its process 
> id) is still running or not. I know that this can be done with OS 
> specific calls. But that is not portable. It can also be done by 
> executing "ps -p 23423" with subprocess module, but that is not portable 
> either. Is there a portable way to do this?
> 
> If not, would it be a good idea to implement this (I think very 
> primitive) function in the os module?

Not only is there no way to do it portably, there is no way to do it
reliably for the general case. The problem is that processes do not have
unique identifiers. A PID only uniquely identifies a running process; once
the process terminates, its PID becomes available for re-use.

On Unix, it's easy enough to detect whether a given PID is in use:
kill(pid, 0) will fail with ESRCH if the pid isn't in use.

But if the PID *is* in use, you don't know whether it's being used for the
process which wrote the PID file, or if that process died and its PID is
now being re-used by another process.

A more reliable approach would be for the creator to write not only its
PID, but also its start time to the file. Any subsequent process which
re-uses the PID is bound to have a later start time. However, the
difference could conceivably be less than a second, and getting the start
time of a process to better than a second isn't portable between Unices,
and may not even be possible.

More reliable still would be for the creator to place a lock on the
PID file, then test for the presence of the lock. Ensure that
testing for the lock doesn't itself lock the file in a way which could
fool other processes testing for the presence of a lock; e.g. have the
creator place an exclusive lock and test by attempting to place a shared
lock.





More information about the Python-list mailing list