How to check if there exists a process with a given pid in Python?
Asked Answered
G

15

145

Is there a way to check to see if a pid corresponds to a valid process? I'm getting a pid from a different source other than from os.getpid() and I need to check to see if a process with that pid doesn't exist on the machine.

I need it to be available in Unix and Windows. I'm also checking to see if the PID is NOT in use.

Gustav answered 20/2, 2009 at 4:22 Comment(6)
Windows is a non-standard OS. These kinds of things are NOT portable. Knowing you cannot have both, which is your priority? Pick one as a priority and edit the question.Hairsplitter
@Hairsplitter Windows is a non-standard OS This is one of the most silly remark I've seen on SO...Cobaltite
@Piotr Dobrogost: Can you provide code that handles POSIX standard unix and non-POSIX standard Windows? If so, please provide an answer that (a) solves the problem and (b) makes it clear that Windows is somehow compliant with the POSIX standard.Hairsplitter
@PiotrDobrogost I think S.Lott's remark was more about implementation details and API support than market share.Pazpaza
Windows certainly has less in common with other popular OSes than the rest do with each other. (Anybody who does web development may liken it to a similarly infamous Microsoft product.) But in response to @S.Lott: I rarely write Python code for Windows that's not supposed to also work on Linux, OSX, BSD, etc, so I honestly don't think 'pick on as a priority' is helpful advice, especially since Python abstracts platform differences away as much as practicable.Warfarin
linux only: import subprocess; subprocess.check_call('ps -p 12345', shell=True); and for cross-platform use psutilCarlsen
S
196

Sending signal 0 to a pid will raise an OSError exception if the pid is not running, and do nothing otherwise.

import os

def check_pid(pid):        
    """ Check For the existence of a unix pid. """
    try:
        os.kill(pid, 0)
    except OSError:
        return False
    else:
        return True
Sadomasochism answered 20/2, 2009 at 4:31 Comment(13)
Also, doesn't this kill the process?Gustav
Works for sure in linux and OSX, I can't speak for Windows. It does not kill the process in the sense that you are asking, it sends signal 0, which is basically "Are you running?".Sadomasochism
Ah, I see. Thanks for the code, but what I really need is something that runs in Windows as well.Gustav
Why SIG_DFL? Signal 0 has no name, and should (to my knowledge) be written as 0, not as SIG_DFL (which does not have a mandated value, and can stand for some other value on other systems).Elinorelinore
In the python signal module, signal 0 is defined as SIG_DFL. Unless I am misinterpreting the module.Sadomasochism
This definitely doesn't work on Windows, as there's no such thing as UNIX-like signals.Nevus
To be complete, you should also check for the error number to make sure it is 3 (catch the exception and check for first arg). This is important if the target process exists but you don't have permission to send signal (for whatever reason).Westney
Supported by windows now. docs.python.org/library/os.html?highlight=os.kill#os.killDes
os.kill is supported on Windows, but os.kill(pid, 0) is the same as os.kill(pid, signal.CTRL_C_EVENT) which may terminate the process (or fail). I get an OSError where errno==EINVAL when I try this on a subprocess.Bop
This code is incorrect 'cause it doesn't take EPERM error into account, returning False for a PID which actually exists. This is the right answer: https://mcmap.net/q/158416/-how-to-check-if-there-exists-a-process-with-a-given-pid-in-pythonAwlwort
Important note- This works only if the process in question is owned by the user running check_pid()Concordant
in python3 os.kill() throws ProcessLookupErrorStoried
@Jason R. Coombs This is the issue about why not "os.kill on Windows should accept zero as signal" : bugs.python.org/issue14480Rodney
P
111

Have a look at the psutil module:

psutil (python system and process utilities) is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network) in Python. [...] It currently supports Linux, Windows, OSX, FreeBSD and Sun Solaris, both 32-bit and 64-bit architectures, with Python versions from 2.6 to 3.4 (users of Python 2.4 and 2.5 may use 2.1.3 version). PyPy is also known to work.

It has a function called pid_exists() that you can use to check whether a process with the given pid exists.

Here's an example:

import psutil
pid = 12345
if psutil.pid_exists(pid):
    print("a process with pid %d exists" % pid)
else:
    print("a process with pid %d does not exist" % pid)

For reference:

Priscillaprise answered 12/7, 2013 at 19:16 Comment(2)
Here's how psutil implements pid_exists() on POSIX. Compare with @Giampaolo Rodolà's answer (author of psutil)Modality
I had an instance where pid_exists stopped being reliable on Windows. It was mis-reporting dead pids as being in use. This is a reminder to keep your psutil module updated from time to time - especially when doing OS upgrades.Vulgarian
M
70

mluebke code is not 100% correct; kill() can also raise EPERM (access denied) in which case that obviously means a process exists. This is supposed to work:

(edited as per Jason R. Coombs comments)

import errno
import os

def pid_exists(pid):
    """Check whether pid exists in the current process table.
    UNIX only.
    """
    if pid < 0:
        return False
    if pid == 0:
        # According to "man 2 kill" PID 0 refers to every process
        # in the process group of the calling process.
        # On certain systems 0 is a valid PID but we have no way
        # to know that in a portable fashion.
        raise ValueError('invalid PID 0')
    try:
        os.kill(pid, 0)
    except OSError as err:
        if err.errno == errno.ESRCH:
            # ESRCH == No such process
            return False
        elif err.errno == errno.EPERM:
            # EPERM clearly means there's a process to deny access to
            return True
        else:
            # According to "man 2 kill" possible error values are
            # (EINVAL, EPERM, ESRCH)
            raise
    else:
        return True

You can't do this on Windows unless you use pywin32, ctypes or a C extension module. If you're OK with depending from an external lib you can use psutil:

>>> import psutil
>>> psutil.pid_exists(2353)
True
Mousey answered 4/8, 2011 at 11:8 Comment(8)
haridsv suggests the test should be e.errno != 3; perhaps e.errno != errno.ESRCHBop
Why? ESRCH means "no such process".Awlwort
Right. Since ESRCH means "no such process", errno != ESRCH means "not no such process" or "process exists", which is very similar to the name of the function. You mentioned specifically EPERM, but what do the other possible error codes imply? It seems incorrect to single out an error code which is loosely related to the intent of the check, whereas ESRCH seems closely related.Bop
You're right. I edited the code which now reflects what you suggested.Awlwort
in python3 os.kill() throws ProcessLookupErrorStoried
Right, but the code above will work with both Python 2 and 3 anyway.Awlwort
@martinkunev: ProcessLookupError inherits from OSErrorSoftshoe
Best answer I saw for Linux on SO. Minor: pylint reports Unused import sys (unused-import)Burk
C
26

The answers involving sending 'signal 0' to the process will work only if the process in question is owned by the user running the test. Otherwise you will get an OSError due to permissions, even if the pid exists in the system.

In order to bypass this limitation you can check if /proc/<pid> exists:

import os

def is_running(pid):
    if os.path.isdir('/proc/{}'.format(pid)):
        return True
    return False

This applies to linux based systems only, obviously.

Concordant answered 25/1, 2017 at 12:33 Comment(4)
wrong. PermissionError means pid exists, you get ProcessLookupError if pid doesn't exist.Modality
The OSError due to denied permission can be differentiated from other ones - either via looking at errno or via catching the more specialized PermissionError/ProcessLookupError exceptions which derive from OSError. Futhermore, you only get the permission error if the process exists. Thus, your example is just an alternative method that works on Linux and some other Unices but it isn't more complete than properly calling os.kill(pid, 0).Softshoe
This solution is not corss-platform. The OP want it be available on Unix and Windows. The /proc procfs only exits on Linux, not even on BSD or OSX.Wawro
This method fails if /proc is mounted hidepid=2, the process won't show in the list if it's owned by another user.Anemochore
M
11

In Python 3.3+, you could use exception names instead of errno constants. Posix version:

import os

def pid_exists(pid): 
    if pid < 0: return False #NOTE: pid == 0 returns True
    try:
        os.kill(pid, 0) 
    except ProcessLookupError: # errno.ESRCH
        return False # No such process
    except PermissionError: # errno.EPERM
        return True # Operation not permitted (i.e., process exists)
    else:
        return True # no error, we can send a signal to the process
Modality answered 25/11, 2013 at 7:5 Comment(0)
N
9

Look here for windows-specific way of getting full list of running processes with their IDs. It would be something like

from win32com.client import GetObject
def get_proclist():
    WMI = GetObject('winmgmts:')
    processes = WMI.InstancesOf('Win32_Process')
    return [process.Properties_('ProcessID').Value for process in processes]

You can then verify pid you get against this list. I have no idea about performance cost, so you'd better check this if you're going to do pid verification often.

For *NIx, just use mluebke's solution.

Nevus answered 20/2, 2009 at 7:20 Comment(1)
This worked well for me. I wanted to check for a process name so swapped out "ProcessID" for "Name" and also converted it into a check for in list to return True or False.Brumley
E
7

Building upon ntrrgc's I've beefed up the windows version so it checks the process exit code and checks for permissions:

def pid_exists(pid):
    """Check whether pid exists in the current process table."""
    if os.name == 'posix':
        import errno
        if pid < 0:
            return False
        try:
            os.kill(pid, 0)
        except OSError as e:
            return e.errno == errno.EPERM
        else:
            return True
    else:
        import ctypes
        kernel32 = ctypes.windll.kernel32
        HANDLE = ctypes.c_void_p
        DWORD = ctypes.c_ulong
        LPDWORD = ctypes.POINTER(DWORD)
        class ExitCodeProcess(ctypes.Structure):
            _fields_ = [ ('hProcess', HANDLE),
                ('lpExitCode', LPDWORD)]

        SYNCHRONIZE = 0x100000
        process = kernel32.OpenProcess(SYNCHRONIZE, 0, pid)
        if not process:
            return False

        ec = ExitCodeProcess()
        out = kernel32.GetExitCodeProcess(process, ctypes.byref(ec))
        if not out:
            err = kernel32.GetLastError()
            if kernel32.GetLastError() == 5:
                # Access is denied.
                logging.warning("Access is denied to get pid info.")
            kernel32.CloseHandle(process)
            return False
        elif bool(ec.lpExitCode):
            # print ec.lpExitCode.contents
            # There is an exist code, it quit
            kernel32.CloseHandle(process)
            return False
        # No exit code, it's running.
        kernel32.CloseHandle(process)
        return True
Erstwhile answered 1/5, 2014 at 14:6 Comment(3)
Actually, according to msdn.microsoft.com/en-us/library/windows/desktop/…, GetExistCodeProcess requires the PROCESS_QUERY_INFORMATION and PROCESS_QUERY_LIMITED_INFORMATION access rights.Muntin
Note that the code is wrong. GetExitCodeProcess receives a handle and a pointer and in this sample it's receiving an ExitCodeProcess structure as the second parameter when it should be only a pointer.Giblet
After OpenProcess, it's a good idea to check GetLastError. An ERROR_ACCESS_DENIED there means the process exists! Here's a complete example using this: gist.github.com/ociule/8a48d2a6b15f49258a87b5f55be29250Ilonailonka
R
4

Combining Giampaolo Rodolà's answer for POSIX and mine for Windows I got this:

import os
if os.name == 'posix':
    def pid_exists(pid):
        """Check whether pid exists in the current process table."""
        import errno
        if pid < 0:
            return False
        try:
            os.kill(pid, 0)
        except OSError as e:
            return e.errno == errno.EPERM
        else:
            return True
else:
    def pid_exists(pid):
        import ctypes
        kernel32 = ctypes.windll.kernel32
        SYNCHRONIZE = 0x100000

        process = kernel32.OpenProcess(SYNCHRONIZE, 0, pid)
        if process != 0:
            kernel32.CloseHandle(process)
            return True
        else:
            return False
Rutherfordium answered 15/7, 2013 at 0:24 Comment(2)
The windows version does not work for me on windows 8.1. You have to check GetExitCodeProcess and make sure you even have access.Erstwhile
Using kernel32.OpenProcess solely is not enough. As here pointed out "if the process exited recently, a pid may still exist for the handle." If kernel32.OpenProcess returns non zero value, we still need kernel32.GetExitCodeProcess further to check the exit code.Pignus
S
3

After trying different solutions, relying on psutil was the best OS agnostic way to accurately say if a PID exists. As suggested above, psutil.pid_exists(pid) works as intended but the downside is, it includes stale process IDs and processes that were terminated recently.

Solution: Check if process ID exists and if it is actively running.

import psutil

def process_active(pid: int or str) -> bool:
    try:
        process = psutil.Process(pid)
    except psutil.Error as error:  # includes NoSuchProcess error
        return False
    if psutil.pid_exists(pid) and process.status() not in (psutil.STATUS_DEAD, psutil.STATUS_ZOMBIE):
        return True
    return False
Spake answered 7/12, 2022 at 17:6 Comment(2)
Work good, is OS agnostic, should be higher ranked ;) Thanks.Dictograph
Just one thing, change the process status check to include anyone except dead and zombies (best practice). Eg process.status() not in (psutil.STATUS_DEAD, psutil.STATUS_ZOMBIE)Dictograph
G
2

This will work for Linux, for example if you want to check if banshee is running... (banshee is a music player)

import subprocess

def running_process(process):
    "check if process is running. < process > is the name of the process."

    proc = subprocess.Popen(["if pgrep " + process + " >/dev/null 2>&1; then echo 'True'; else echo 'False'; fi"], stdout=subprocess.PIPE, shell=True)

    (Process_Existance, err) = proc.communicate()
    return Process_Existance

# use the function
print running_process("banshee")
Gandy answered 26/5, 2014 at 23:0 Comment(1)
This method clearly is inferior in comparison to either using os.kill(pid, 0) or looking at /proc/{pid}. Instead of executing one syscall your code forks a child, execs a shell in that child, the shell interprets your superfluous mini shell-script, the shell forks another child that execs pgrep and finally pgrep iterates over /proc. Your answer doesn't answer the posted question. The OP asked for a method given a PID. Your method requires a process name.Softshoe
M
2

In Windows, you can do it in this way:

import ctypes
PROCESS_QUERY_INFROMATION = 0x1000
def checkPid(pid):
    processHandle = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_INFROMATION, 0,pid)
    if processHandle == 0:
        return False
    else:
        ctypes.windll.kernel32.CloseHandle(processHandle)
    return True

First of all, in this code you try to get a handle for process with pid given. If the handle is valid, then close the handle for process and return True; otherwise, you return False. Documentation for OpenProcess: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684320%28v=vs.85%29.aspx

Minotaur answered 21/1, 2015 at 11:19 Comment(0)
C
0

The following code works on both Linux and Windows, and not depending on external modules

import os
import subprocess
import platform
import re

def pid_alive(pid:int):
    """ Check For whether a pid is alive """


    system = platform.uname().system
    if re.search('Linux', system, re.IGNORECASE):
        try:
            os.kill(pid, 0)
        except OSError:
            return False
        else:
            return True
    elif re.search('Windows', system, re.IGNORECASE):
        out = subprocess.check_output(["tasklist","/fi",f"PID eq {pid}"]).strip()
        # b'INFO: No tasks are running which match the specified criteria.'

        if re.search(b'No tasks', out, re.IGNORECASE):
            return False
        else:
            return True
    else:
        raise RuntimeError(f"unsupported system={system}")

It can be easily enhanced in case you need

  1. other platforms
  2. other language
Cricket answered 20/8, 2020 at 1:56 Comment(0)
E
0

I found that this solution seems to work well in both windows and linux. I used psutil to check.

import psutil
import subprocess
import os
p = subprocess.Popen(['python', self.evaluation_script],stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 

pid = p.pid

def __check_process_running__(self,p):
    if p is not None:
        poll = p.poll()
        if poll == None:
            return True
    return False
    
def __check_PID_running__(self,pid):
    """
        Checks if a pid is still running (UNIX works, windows we'll see)
        Inputs:
            pid - process id
        returns:
            True if running, False if not
    """
    if (platform.system() == 'Linux'):
        try:
            os.kill(pid, 0)
            if pid<0:               # In case code terminates
                return False
        except OSError:
            return False 
        else:
            return True
    elif (platform.system() == 'Windows'):
        return pid in (p.pid for p in psutil.process_iter())
Evanston answered 14/10, 2020 at 1:50 Comment(0)
A
0

Another option for Windows is through the pywin32 package:

pid in win32process.EnumProcesses()

The win32process.EnumProcesses() returns PIDs for currently running processes.

Anadem answered 11/3, 2021 at 0:10 Comment(0)
M
-2

I'd say use the PID for whatever purpose you're obtaining it and handle the errors gracefully. Otherwise, it's a classic race (the PID may be valid when you check it's valid, but go away an instant later)

Miran answered 20/2, 2009 at 7:39 Comment(3)
I should have been more specific - I'm checking for the INVALIDITY. So, I basically want to be able to see if a pid is NOT in use.Gustav
But what will you do with that answer? The instant after you've gained that knowledge, something might use that pid.Miran
@Miran - that's alright if something is using it after I gain that knowledge, and I understand what you're saying about the race condition, but I can assure you that it doesn't apply for my situation.Gustav

© 2022 - 2024 — McMap. All rights reserved.