Skip to content

Commit 35614b0

Browse files
committed
interrupt fix
1 parent 8f58dc8 commit 35614b0

1 file changed

Lines changed: 127 additions & 7 deletions

File tree

‎hackrfpy/src/hackrfpy/core.py‎

Lines changed: 127 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -77,8 +77,10 @@ def _ensure_console_logging() -> None:
7777
# ---- platform interrupt plumbing -------------------------------------------
7878
# hackrf_* tools flush + close cleanly on SIGINT. On Windows SIGINT can't be
7979
# delivered to a child; the equivalent is CTRL_BREAK_EVENT, which requires
80-
# the child to be in its own process group. Best-effort: exercised on POSIX,
81-
# untested on Windows.
80+
# the child to be in its own process group. Both paths are exercised by
81+
# tests/test_interrupt_clean.py, which asserts the interrupt signal itself
82+
# arrives (not the terminate() escalation) and that a handler's final flush
83+
# survives into the drained output -- the no-truncated-capture contract.
8284
if sys.platform == "win32": # pragma: no cover
8385
_CREATION_FLAGS = subprocess.CREATE_NEW_PROCESS_GROUP
8486
_INTERRUPT_SIGNAL = signal.CTRL_BREAK_EVENT
@@ -100,13 +102,107 @@ def _interrupt(proc: subprocess.Popen[Any]) -> None:
100102
# It does NOT survive `kill -9` / power loss (no handler runs); that needs an
101103
# OS dead-man (Linux PR_SET_PDEATHSIG / Windows Job Object) which is platform-
102104
# split work deferred to a later pass.
103-
# TODO(os-deadman): Linux prctl(PR_SET_PDEATHSIG); Windows Job Object with
104-
# JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE. Survives hard-kill of the parent.
105+
# ---- OS dead-man ------------------------------------------------------------
106+
# The atexit backstop never runs on SIGKILL / TerminateProcess, so a hard-
107+
# killed parent could orphan a live transmitter. The dead-man asks the OS
108+
# itself to end the child when the parent dies, surviving any kind of parent
109+
# death:
110+
# Linux : the child sets PR_SET_PDEATHSIG to SIGINT in preexec, so the
111+
# kernel delivers the CLEAN interrupt (same flush path as stop())
112+
# the moment the parent dies. A getppid() check closes the fork-
113+
# window race where the parent died before prctl ran.
114+
# Windows : the child is assigned to a Job Object with KILL_ON_JOB_CLOSE.
115+
# The parent's death closes its handles; the OS then terminates
116+
# the whole job -- including the .bat -> python launcher tree.
117+
# The job handle lives on the _Process; dropping every reference
118+
# to a running protected handle therefore lets GC close the job
119+
# and reap the child, which is the dead-man philosophy applied
120+
# to a leaked handle.
121+
# macOS : no equivalent primitive; the atexit backstop remains the only
122+
# net there.
123+
# Scope: handle-mode spawns, gated exactly like the atexit registry below
124+
# (TX always, RX unless backstop_rx=False). Exercised by
125+
# tests/test_deadman.py, including a real parent hard-kill.
105126
#
106127
# TX handles are ALWAYS registered (an orphaned transmitter is a regulatory /
107128
# interference problem). RX handles are registered by default but can opt out
108129
# (an orphaned receiver only wastes disk, and fire-and-forget is occasionally
109130
# wanted).
131+
if sys.platform == "win32":
132+
def _deadman_preexec() -> Any:
133+
return None # Windows path uses the Job Object
134+
135+
def _deadman_attach(proc: subprocess.Popen[Any]) -> Any:
136+
import ctypes
137+
from ctypes import wintypes
138+
139+
class _BasicLimits(ctypes.Structure):
140+
_fields_ = [("PerProcessUserTimeLimit", ctypes.c_int64),
141+
("PerJobUserTimeLimit", ctypes.c_int64),
142+
("LimitFlags", wintypes.DWORD),
143+
("MinimumWorkingSetSize", ctypes.c_size_t),
144+
("MaximumWorkingSetSize", ctypes.c_size_t),
145+
("ActiveProcessLimit", wintypes.DWORD),
146+
("Affinity", ctypes.c_size_t),
147+
("PriorityClass", wintypes.DWORD),
148+
("SchedulingClass", wintypes.DWORD)]
149+
150+
class _IoCounters(ctypes.Structure):
151+
_fields_ = [(n, ctypes.c_uint64) for n in (
152+
"ReadOperationCount", "WriteOperationCount",
153+
"OtherOperationCount", "ReadTransferCount",
154+
"WriteTransferCount", "OtherTransferCount")]
155+
156+
class _ExtendedLimits(ctypes.Structure):
157+
_fields_ = [("BasicLimitInformation", _BasicLimits),
158+
("IoInfo", _IoCounters),
159+
("ProcessMemoryLimit", ctypes.c_size_t),
160+
("JobMemoryLimit", ctypes.c_size_t),
161+
("PeakProcessMemoryUsed", ctypes.c_size_t),
162+
("PeakJobMemoryUsed", ctypes.c_size_t)]
163+
164+
_KILL_ON_JOB_CLOSE = 0x2000
165+
_EXTENDED_LIMIT_CLASS = 9
166+
try:
167+
k32 = ctypes.windll.kernel32
168+
job = k32.CreateJobObjectW(None, None)
169+
if not job:
170+
return None
171+
info = _ExtendedLimits()
172+
info.BasicLimitInformation.LimitFlags = _KILL_ON_JOB_CLOSE
173+
if not k32.SetInformationJobObject(
174+
job, _EXTENDED_LIMIT_CLASS, ctypes.byref(info),
175+
ctypes.sizeof(info)):
176+
k32.CloseHandle(job)
177+
return None
178+
if not k32.AssignProcessToJobObject(
179+
job, wintypes.HANDLE(int(proc._handle))): # type: ignore[attr-defined]
180+
k32.CloseHandle(job)
181+
return None
182+
return job
183+
except OSError:
184+
return None # best-effort: never block a spawn
185+
else:
186+
def _deadman_preexec() -> Any:
187+
if not sys.platform.startswith("linux"):
188+
return None # macOS: no pdeathsig primitive
189+
try:
190+
import ctypes
191+
libc = ctypes.CDLL(None, use_errno=True)
192+
except OSError:
193+
return None
194+
_PR_SET_PDEATHSIG = 1
195+
196+
def _preexec() -> None:
197+
libc.prctl(_PR_SET_PDEATHSIG, signal.SIGINT, 0, 0, 0)
198+
if os.getppid() == 1: # parent died in the fork window
199+
os.kill(os.getpid(), signal.SIGINT)
200+
return _preexec
201+
202+
def _deadman_attach(proc: subprocess.Popen[Any]) -> Any:
203+
return None # POSIX path is the preexec
204+
205+
110206
class _Stoppable(Protocol):
111207
# What the atexit backstop actually needs. _Process and PersistentReceiver
112208
# both satisfy it; a Protocol keeps _LIVE honest about holding both without
@@ -153,6 +249,7 @@ def __init__(self, proc: subprocess.Popen[Any], owner: HackRF,
153249
kind: str = "rx") -> None:
154250
self._proc = proc
155251
self._owner = owner
252+
self._job: Any = None # Windows Job Object (OS dead-man)
156253
self._kind = kind # "rx" | "tx" -- for atexit messaging
157254
self._stopped = False
158255
self._out_chunks: list[bytes] = []
@@ -170,7 +267,13 @@ def __init__(self, proc: subprocess.Popen[Any], owner: HackRF,
170267
@staticmethod
171268
def _drain(stream: Any, sink: list[bytes]) -> None:
172269
try:
173-
for chunk in iter(lambda: stream.read(65536), b""):
270+
# read1(): return as soon as ANY bytes are available (at most one
271+
# raw read), b"" only at EOF. Plain read(65536) on a BufferedReader
272+
# BLOCKS until 64 KB accumulate, so a child's small writes (e.g.
273+
# hackrf_transfer's ~60-byte-per-second stats lines) were invisible
274+
# to the parent until process exit -- output was only "live" if the
275+
# child flooded past the buffer size.
276+
for chunk in iter(lambda: stream.read1(65536), b""):
174277
sink.append(chunk)
175278
# Bound retained output: drop oldest chunks once over the cap,
176279
# always keeping at least the latest one. Prevents unbounded
@@ -191,7 +294,18 @@ def stop(self, grace: float = 2.0) -> tuple[bytes, bytes, int | None]:
191294
try:
192295
self._proc.wait(timeout=grace)
193296
except subprocess.TimeoutExpired:
297+
# Escalation ladder, each rung bounded and REAPED: a child
298+
# that ignores the interrupt gets terminate(); one that
299+
# survives that gets kill(). stop() previously fired
300+
# terminate() and returned without waiting, so a hardened
301+
# child could outlive stop() and result() reported
302+
# returncode None.
194303
self._proc.terminate()
304+
try:
305+
self._proc.wait(timeout=grace)
306+
except subprocess.TimeoutExpired:
307+
self._proc.kill()
308+
self._proc.wait()
195309
self._stopped = True
196310
_LIVE.discard(self) # no longer needs the atexit backstop
197311
return self.result()
@@ -550,12 +664,18 @@ def _run(self, argv: list[Any], *, mode: str = "blocking",
550664
if mode == "stream":
551665
return self._stream(resolved, text=text, read_samples=read_samples)
552666
if mode == "handle":
667+
# Tier C (OS dead-man): same gate as the atexit registry below.
668+
protected = kind == "tx" or self.backstop_rx
669+
preexec = _deadman_preexec() if protected else None
553670
proc = subprocess.Popen(resolved, stdout=subprocess.PIPE,
554671
stderr=subprocess.PIPE,
555-
creationflags=_CREATION_FLAGS)
672+
creationflags=_CREATION_FLAGS,
673+
preexec_fn=preexec)
556674
handle = _Process(proc, self, kind=kind)
675+
if protected:
676+
handle._job = _deadman_attach(proc)
557677
# Tier B: TX always backstopped; RX backstopped unless opted out.
558-
if kind == "tx" or self.backstop_rx:
678+
if protected:
559679
_register_live(handle)
560680
return handle
561681

0 commit comments

Comments
 (0)