Signals

In simplistic terms, a signal is an event. A signal is used to interrupt the execution of a running function. The signals are always executed in the main Python thread.

Signal Functions

There are a number of functions implemented in the signal module. I will outline the must-know functions amongst them.

1. signal.alarm(time):

If you want to raise the SIGALRM signal then you can set the signal.alarm(time) function with the specified time in seconds. If the time is set to 0, then it disables the alarm Setting a new alarm cancels any previously scheduled alarms.

2. signal.pause() The process sleeps until a signal is received. And then the signal handler is called.

3. signal.raise_signal(number of signal): It sends a signal to the calling process

4. signal.setitimer(which, seconds, interval) This function accepts float number of seconds which we can use to raise a signal. Also after that, for each interval, the signal is sent to the process.

5. signal.siginterrupt(signalnum, flag): It changes system call restart behaviour. If the flag is False then the system calls are restarted when they are interrupted by signal signalnum If the flag is True then the system calls are interrupted

6. signal.getsignal(signalnum)

It takes the signal and returns the handler.

7. signal.signal(signalnum, handler): Lastly and most importantly, I wanted to cover the functional signal() This function sets the handler whenever the signal signalnum is received. The handler is essentially a Python function/callable that takes in either two of the arguments:

  • The signal number

  • Current stack frame (or signal.SIG_IGN or signal.SIG_DFL) as arguments.

In a multi-threaded application, it can only be called from the main thread

Last updated