-
-
Save nelsestu/8dc2e09356f701134283d21097f232bb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ctypes | |
import win32event, winerror | |
class ExitCodeProcess(ctypes.Structure): | |
_fields_ = [ | |
('hProcess', ctypes.c_void_p), # HANDLE | |
('lpExitCode', ctypes.POINTER(ctypes.c_ulong)) # LPDWORD | |
] | |
def pid_exists(pid): | |
"""Check whether a process with the given pid exists. Works on Windows only. | |
Works even if the process is not owned by the current user.""" | |
kernel32 = ctypes.windll.kernel32 | |
process = kernel32.OpenProcess(win32event.SYNCHRONIZE, 0, pid) | |
if not process: | |
if kernel32.GetLastError() == winerror.ERROR_ACCESS_DENIED: | |
# Access is denied. This means the process exists! | |
return True | |
return False | |
ec = ExitCodeProcess() | |
out = kernel32.GetExitCodeProcess(process, ctypes.byref(ec)) | |
if not out: | |
if kernel32.GetLastError() == winerror.ERROR_ACCESS_DENIED: | |
# Access is denied. This means the process exists! | |
kernel32.CloseHandle(process) | |
return True | |
kernel32.CloseHandle(process) | |
return False | |
elif bool(ec.lpExitCode): | |
# There is an exit code, it quit | |
kernel32.CloseHandle(process) | |
return False | |
# No exit code, it's running. | |
kernel32.CloseHandle(process) | |
return True | |
print(pid_exists(14444)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment