Created
January 20, 2020 09:50
-
-
Save ociule/8a48d2a6b15f49258a87b5f55be29250 to your computer and use it in GitHub Desktop.
This file contains hidden or 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)) |
Sounds like a bug somewhere. I do not do much work nowadays with the win32 API so I'm not able to debug it, sorry. Hope you find a good solution to your issue.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@ociule
the code does not always, if a process is launched by subprocess with detached mode, or shell=True, and then killing the process using task manager, will still show pid exists and returns true.
The below is the code i used to invoke
pid_exits()
which peridically checks if
pid_to_monitor
exits, if it does not then it launches example.py using subprocess, but then if the launched process is killed, it still detects process is running.