-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy path_subprocess_lifecycle.py
More file actions
133 lines (114 loc) · 4.02 KB
/
Copy path_subprocess_lifecycle.py
File metadata and controls
133 lines (114 loc) · 4.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
"""Process-lifecycle helpers shared by `idalib_pool.py` and `ida_mcp.py`.
One PID registry, one atexit handler, one terminate-or-kill helper, and the
two TCP-port helpers used by the MCP wrapper. Both modules `import * from`
this; nothing else in the codebase should touch the registry directly.
"""
from __future__ import annotations
import atexit
import os
import signal as _signal
import socket
import subprocess
import sys
import time
from multiprocessing.process import BaseProcess
from subprocess import Popen
from typing import Union
# Module-level registry of every IDA-related subprocess we've spawned. The
# `atexit` handler at the bottom taskkills any survivor regardless of how
# Python exits — Ctrl-C (sys.exit(130)), uncaught exception, or `os._exit`
# from a finalizer all still run atexit. Owners must `unregister(pid)` on
# clean shutdown so the atexit handler is a no-op on the happy path.
_SPAWNED_PIDS: set[int] = set()
def register(pid: int | None) -> None:
"""Add `pid` to the survivor registry. None is a no-op."""
if pid is not None:
_SPAWNED_PIDS.add(pid)
def unregister(pid: int | None) -> None:
"""Remove `pid` from the survivor registry. None is a no-op."""
if pid is not None:
_SPAWNED_PIDS.discard(pid)
def _kill_tracked_pids() -> None:
if not _SPAWNED_PIDS:
return
pids = list(_SPAWNED_PIDS)
_SPAWNED_PIDS.clear()
for pid in pids:
try:
if sys.platform == "win32":
subprocess.run(
["taskkill", "/F", "/PID", str(pid)],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=5,
creationflags=subprocess.CREATE_NO_WINDOW,
)
else:
os.kill(pid, _signal.SIGKILL)
except Exception:
pass
atexit.register(_kill_tracked_pids)
def pick_free_port(host: str = "127.0.0.1") -> int:
"""Bind to an ephemeral port, close, return the number. Tiny TOCTOU
window between our close and the server's bind, but negligible in
practice — a collision shows up as a loud server-startup failure."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((host, 0))
return s.getsockname()[1]
def wait_for_port(host: str, port: int, timeout: float) -> bool:
"""Block until `host:port` accepts a TCP connection or `timeout` elapses."""
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(0.5)
try:
s.connect((host, port))
return True
except OSError:
time.sleep(0.2)
return False
def terminate_proc(
proc: Union[Popen, BaseProcess, None],
*,
timeout: float = 5.0,
) -> None:
"""Best-effort `terminate → wait → kill` dance, swallowing all errors.
Accepts either `subprocess.Popen` (idalib-mcp wrapper) or
`multiprocessing.Process` (idalib pool worker). Both expose
`terminate()` and `kill()` with compatible semantics; only the wait
method differs (`wait(timeout)` vs `join(timeout)` + `is_alive()`).
"""
if proc is None:
return
try:
proc.terminate()
except Exception:
pass
try:
if isinstance(proc, BaseProcess):
proc.join(timeout)
still_alive = proc.is_alive()
else:
try:
proc.wait(timeout=timeout)
still_alive = False
except subprocess.TimeoutExpired:
still_alive = True
except Exception:
still_alive = True
if still_alive:
try:
proc.kill()
except Exception:
pass
try:
if isinstance(proc, BaseProcess):
proc.join(timeout=2)
else:
proc.wait(timeout=2)
except Exception:
pass
try:
unregister(proc.pid)
except Exception:
pass