- 1 year ago
How do I set signal handler to multiprocessing.Process?
Comment
1 / 1
In Python's multiprocessing
module, you can set a signal handler for a multiprocessing.Process
using the signal
module. Here's how you can do it:
pythonimport multiprocessing
import signal
def signal_handler(signum, frame):
print(f"Received signal {signum} in process {multiprocessing.current_process().name}")
def worker():
# Set the signal handler for this process
signal.signal(signal.SIGINT, signal_handler)
print(f"Worker process {multiprocessing.current_process().name} starting")
# Simulate some work
while True:
pass
if __name__ == "__main__":
# Create a new process and start it
process = multiprocessing.Process(target=worker)
process.start()
try:
# Wait for the process to finish
process.join()
except KeyboardInterrupt:
# Send SIGINT (Ctrl+C) to the child process
process.terminate()
In this example, the signal_handler
function is defined to handle the SIGINT
signal (Ctrl+C). You then set this handler for the child process using the signal.signal
function within the worker
function. Finally, in the main block, you create a new process, start it, and handle keyboard interrupts (Ctrl+C) to terminate the child process.
Keep in mind that signal handling can be complex, especially when dealing with multiple processes. Make sure you handle signals carefully to avoid unexpected behavior.