Check if a process with given PID is still running (cross-platform). Args: pid: Process ID to check Returns: True if process exists, False otherwise
(pid: int)
| 17 | |
| 18 | |
| 19 | def is_process_alive(pid: int) -> bool: |
| 20 | """ |
| 21 | Check if a process with given PID is still running (cross-platform). |
| 22 | |
| 23 | Args: |
| 24 | pid: Process ID to check |
| 25 | |
| 26 | Returns: |
| 27 | True if process exists, False otherwise |
| 28 | """ |
| 29 | if pid <= 0: |
| 30 | return False |
| 31 | |
| 32 | try: |
| 33 | # Unix/Linux/macOS: send signal 0 (doesn't actually send signal, just checks) |
| 34 | if platform.system() != "Windows": |
| 35 | os.kill(pid, 0) |
| 36 | return True |
| 37 | else: |
| 38 | # Windows: Try to open process handle |
| 39 | import ctypes |
| 40 | |
| 41 | windll = getattr(ctypes, "windll") |
| 42 | kernel32 = windll.kernel32 |
| 43 | PROCESS_QUERY_INFORMATION = 0x0400 |
| 44 | handle = kernel32.OpenProcess(PROCESS_QUERY_INFORMATION, False, pid) |
| 45 | if handle: |
| 46 | kernel32.CloseHandle(handle) |
| 47 | return True |
| 48 | return False |
| 49 | except (OSError, ProcessLookupError): |
| 50 | return False |
| 51 | except KeyboardInterrupt as ki: |
| 52 | handle_keyboard_interrupt(ki) |
| 53 | raise |
| 54 | except Exception as e: |
| 55 | logger.warning(f"Error checking if PID {pid} is alive: {e}") |
| 56 | return False # Assume dead if we can't check |