Skip to content

Commit 3caa1bb

Browse files
committed
Add signal handler so axexit functions run
1 parent dc7f2e3 commit 3caa1bb

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

runusb/__main__.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,10 +108,33 @@ class LEDs(IntEnum):
108108
def __init__(self) -> None:
109109
if IS_PI:
110110
LOGGER.debug("Configuring LED controller")
111+
self._register_exit()
111112
atexit.register(GPIO.cleanup) # type: ignore[attr-defined]
112113
GPIO.setmode(GPIO.BCM)
113114
GPIO.setup([led.value for led in self.LEDs], GPIO.OUT, initial=GPIO.LOW)
114115

116+
def _register_exit(self) -> None:
117+
"""
118+
Ensure `atexit` triggers on `SIGTERM`.
119+
120+
> The functions registered via [`atexit`] are not called when the program is
121+
killed by a signal not handled by Python
122+
"""
123+
124+
if signal.getsignal(signal.SIGTERM) != signal.SIG_DFL:
125+
# If a signal handler is already present for SIGTERM,
126+
# this is sufficient for `atexit` to trigger, so do nothing.
127+
return
128+
129+
def handle_signal(handled_signum: int, frame) -> None:
130+
"""Semi-default signal handler for SIGTERM, enough for atexit."""
131+
USERCODE_LOGGER.error(signal.strsignal(handled_signum))
132+
exit(128 + handled_signum) # 143 for SIGTERM
133+
134+
# Add the null-ish signal handler
135+
signal.signal(signal.SIGTERM, handle_signal)
136+
137+
115138
def mark_start(self) -> None:
116139
if IS_PI:
117140
GPIO.output(self.LEDs.BOOT_100, GPIO.HIGH)

0 commit comments

Comments
 (0)