Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, without using the /proc filesystem, how do I tell if a given PID is running?

Say I have a PID, like 555. I want to see if that pid is running or has completed. I can check /proc/ but I don't have access to that in my production environment. What's the best way to do this, short of something hackish like opening a pipe to "ps"?

like image 773
Ken Kinder Avatar asked Dec 29 '10 03:12

Ken Kinder


2 Answers

Use the os.kill() function with a signal number of 0. If the process pid exists, then the call will be successful, else it will raise an OSError exception:

try:
    os.kill(pid, 0)
    print("process exists")
except OSError:
    print("process does not exist")

The documentation for kill(2) on my system says:

The kill() function sends the signal given by sig to pid, a process or a group of processes. Sig may be one of the signals specified in sigaction(2) or it may be 0, in which case error checking is performed but no signal is actually sent. This can be used to check the validity of pid.

like image 52
Greg Hewgill Avatar answered Oct 13 '22 00:10

Greg Hewgill


Use os.kill() as mentioned by Greg, but realize that the kill system call tests not whether the process exists, but whether you can send a kill to the process. One failure mode is if the process doesn't exist, but another is that you do not have permission to kill it. To differentiate, you have to check the exception:

try:
   os.kill(pid, 0)
   print 'Process exists and we can kill it'
except OSError, e:
   if e.errno == 1:
      print 'Process exists, but we cannot kill it'
   else:
      raise

This is not required if you know you are always going to have permission to kill the process you are checking for, say because you are running as root or the process is known to be running under the same UID as the process checking it.

like image 27
Sean Reifschneider Avatar answered Oct 13 '22 00:10

Sean Reifschneider