Signals are software interrupts that are sent to the program to notify the program of significant events which can be used to execute a special code.They are generated by the system or can be sent from one process to another. In this blog, we will see how to handle the signals in python and control the execution of your python program.
Receiving a signal:
A callback function called signal handler is invoked when signals are received. The arguments to the signal handler are the signal number and the stack frame from the point in your program that was interrupted by the signal.
import signal import time def handler(signum, frame): print('handler called') signal.signal(signal.SIGINT, handler) time.sleep(20) # Press Ctrl+C
If we run the above code and press Ctrl+C, the handler function gets called and
handler called gets printed.
Raising a signal:
We can raise a signal in a process using the raise_signal() method. It'll send the given signal to the calling process.
import signal from datetime import datetime def handler(signum, frame): print('Signal raised :',datetime.now()) signal.signal(signal.SIGINT, handler) print('Before raising :',datetime.now()) time.sleep(3) signal.raise_signal(signal.SIGINT) print('After raising :',datetime.now())
Before raising : 2022-08-04 16:32:10.192107 Signal raised : 2022-08-04 16:32:13.194372 After raising : 2022-08-04 16:32:13.194975
Ignoring a signal:
For ignoring a signal, register SIG_IGN as the handler. Default handler for SIGINT is replaced with SIG_IGN, and registers a handler for SIGUSR1. signal.pause() is used to wait for the signal to be received.
import signal import os import time def fun_exit(sig, stack): raise SystemExit('Exiting') signal.signal(signal.SIGINT, signal.SIG_IGN) signal.signal(signal.SIGUSR1, fun_exit) print('PID is: ', os.getpid()) signal.pause() # To quit the program use control + Z
PID is: 96481 ^C^C^C^C^C^C^Z
In this example, we ignore SIGINT and raise SystemExit when we see SIGUSR. Each ^C represents an attempt to use Ctrl-C to kill the script from the terminal.