Back
+15 XP
Concept

Handling OS Signals with the signal Module

Operating systems send signals (`SIGINT` from Ctrl+C, `SIGTERM` from Docker). The `signal` module intercepts them for graceful resource cleanup before termination 🚦.

python
import signal

def handle_sigint(signum, frame):
    print("\nIntercepted SIGINT (Ctrl+C)! Cleaning up... 🚦")

# Register custom signal handler:
signal.signal(signal.SIGINT, handle_sigint)
print(f"Signal SIGINT registered: {signal.SIGINT} 🚦")

# 104. Handling OS Signals with the signal Module Operating systems send signals (`SIGINT` from Ctrl+C, `SIGTERM` from Docker). The `signal` module intercepts them for graceful resource cleanup before termination 🚦. ```python import signal def handle_sigint(signum, frame): print("\nIntercepted SIGINT (Ctrl+C)! Cleaning up... 🚦") # Register custom signal handler: signal.signal(signal.SIGINT, handle_sigint) print(f"Signal SIGINT registered: {signal.SIGINT} 🚦") ``` In Unix, `SIGKILL` (9) and `SIGSTOP` cannot be caught or ignored. But `SIGTERM` (15) and `SIGINT` (2) can and should be trapped for clean server shutdown! 🚦 --- ### Question Which Unix signal is triggered when a user presses Ctrl+C in their terminal? 🧠 - [ ] a. `signal.SIGINT` (Interrupt Signal) 🚦 - [ ] b. `signal.SIGKILL` - [ ] c. `signal.SIGSEGV` - [ ] d. `signal.SIGPIPE` --- ### Challenge Import `signal`. Print whether `hasattr(signal, 'SIGINT')` and `hasattr(signal, 'SIGTERM')` are both `True`. 🎯 <details> <summary>Solution</summary> ```python import signal print(hasattr(signal, "SIGINT") and hasattr(signal, "SIGTERM")) ``` </details>

Checkpoint

Which Unix signal is triggered when a user presses Ctrl+C in their terminal? 🧠

Practice

Import `signal`. Print whether `hasattr(signal, 'SIGINT')` and `hasattr(signal, 'SIGTERM')` are both `True`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks