Linux Signal Handling & Graceful Shutdown (SIGTERM)
Container platforms (Kubernetes, Docker) shut down services by sending `SIGTERM` before hard-killing with `SIGKILL`. Intercepting `signal.SIGTERM` allows servers to drain active requests, commit transactions, and close files cleanly 🛑.
import signal
shutdown_initiated = False
def handle_sigterm(signum, frame):
global shutdown_initiated
shutdown_initiated = True
signal.signal(signal.SIGTERM, handle_sigterm)
# Trigger simulated shutdown:
signal.raise_signal(signal.SIGTERM)
print(f"Graceful drain triggered: {shutdown_initiated} 🛑")
# 118. Linux Signal Handling & Graceful Shutdown (SIGTERM) Container platforms (Kubernetes, Docker) shut down services by sending `SIGTERM` before hard-killing with `SIGKILL`. Intercepting `signal.SIGTERM` allows servers to drain active requests, commit transactions, and close files cleanly 🛑. ```python import signal shutdown_initiated = False def handle_sigterm(signum, frame): global shutdown_initiated shutdown_initiated = True signal.signal(signal.SIGTERM, handle_sigterm) # Trigger simulated shutdown: signal.raise_signal(signal.SIGTERM) print(f"Graceful drain triggered: {shutdown_initiated} 🛑") ``` When integrating with asyncio, use `loop.add_signal_handler(signal.SIGTERM, callback)` instead of `signal.signal` to ensure shutdown callbacks execute safely within the event loop's main thread ⚡! --- ### Question Why is it impossible for any user application to catch or ignore `signal.SIGKILL` (signal 9)? 🧠- [ ] a. `SIGKILL` is intercepted and executed directly by the Linux kernel, killing the process without notifying user space 🛑 - [ ] b. Python handles signal 9 inside an internal private thread - [ ] c. Signals higher than 8 require root Linux user permissions - [ ] d. `SIGKILL` only applies to compiled C binaries --- ### Challenge Register a signal handler for `signal.SIGUSR1` that appends `'GOT_SIG'` to list `events`. Trigger with `signal.raise_signal(signal.SIGUSR1)` and print `events[0]`. 🎯 <details> <summary>Solution</summary> ```python import signal events = [] def handler(sig, frame): events.append('GOT_SIG') signal.signal(signal.SIGUSR1, handler) signal.raise_signal(signal.SIGUSR1) print(events[0]) ``` </details>