45. Handling Signals in Python
Here are 10 Python code snippets demonstrating how to handle signals using the signal module. The signal module allows you to capture and respond to various system signals, such as termination signals, alarms, etc.
1. Basic Signal Handling
Handling the SIGINT (Ctrl+C) signal.
Copy
import signal
import time
def signal_handler(sig, frame):
print('SIGINT received, exiting...')
exit(0)
# Register signal handler for SIGINT
signal.signal(signal.SIGINT, signal_handler)
print("Press Ctrl+C to exit")
while True:
time.sleep(1)This example captures SIGINT and gracefully exits the program when Ctrl+C is pressed.
2. Handling Multiple Signals
Handling both SIGINT and SIGTERM signals.
Copy
In this example, both SIGINT and SIGTERM are handled by the same handler.
3. Setting a Timeout with SIGALRM
Using SIGALRM to set a timeout for a task.
Copy
This example sets an alarm that triggers SIGALRM after 5 seconds, calling timeout_handler.
4. Ignoring a Signal
Using signal.SIG_IGN to ignore a signal.
Copy
This code ignores the SIGINT signal (Ctrl+C) and does nothing when it is received.
5. Handling Signals with a Custom Function
Define a custom function for handling signals.
Copy
This example defines a custom function custom_handler to respond to the SIGQUIT signal.
6. Catching Signals in a Child Process
Capture signals in a child process spawned by os.fork().
Copy
This snippet demonstrates how a child process can catch signals using the signal module.
7. Using signal.sigtimedwait for Handling Signals
Blocking until a signal is received.
Copy
In this example, the process waits for SIGALRM with a timeout using sigtimedwait.
8. Handling Signals in Threads
Handling signals inside a thread.
Copy
This demonstrates how to handle signals in the main thread while running a background thread.
9. Using signal.pause
Pause the program until a signal is received.
Copy
The signal.pause() function causes the program to wait indefinitely for any signal to be received.
10. Handling Signals in a Daemon
Handling signals in a daemon process.
Copy
In this example, the parent process sends a SIGTERM signal to the daemon (child process), which handles it with a signal handler.
These examples demonstrate how you can use Python's signal module to handle various types of signals in different scenarios, making your program more flexible and responsive to external events.
Last updated