Python Signal Module with Examples

The Signal module comes in useful when we need to handle specific signals in Python.

Signal

A Signal is a way for a program to receive information from the Operating System. When the operating system receives specific events, it can send that programs in the form of signals.

When we press the keystrokes Ctrl + C on our keyboard, for example, the Operating System generates a signal that is sent on to programs. The signal SIGINT is generated and sent to the programs for this particular combination.

There is a standard protocol for assigning these signals, which are commonly short for integers, in all common operating systems.

The signal module in Python is where these signals are defined.

Importing signal module

import signal

You can use signal.valid _signals to see all of the valid signals in your system (depending on the operating system)

Example

Approach:

  • Import signal module using the import keyword.
  • Get all the valid signals on our OS using the valid_signals() function.
  • Store it in another variable.
  • Print all the above valid signals.
  • The Exit of the Program.

Below is the implementation:

# Import signal module using the import keyword
import signal
# Get all the valid signals on our OS using the valid_signals() function
# Store it in another variable.
validsignls = signal.valid_signals()
# Print all the above valid signals 
print(validsignls)

Output:

{<Signals.SIGINT: 2>, <Signals.SIGILL: 4>, <Signals.SIGFPE: 8>,
 <Signals.SIGSEGV: 11>, <Signals.SIGTERM: 15>, <Signals.SIGBREAK: 21>,
 <Signals.SIGABRT: 22>}

Now, for all signals, the OS will assign some default actions to each program.

Instead, we can use signal handlers to achieve our desired behavior.

Signal Handler in Python

A Signal Handler is a user-defined function that handles Python signals.

If we consider the signal SIGINT (Interrupt Signal), the default behavior is to terminate the current program.

Instead, we may set a signal handler to detect this signal and perform our custom processing!

Example

Approach:

  • Import signal module using the import keyword
  • Import time module using the import keyword
  • create a function signalHandler which accepts the signal number and framenumber as arguments
  • print the value of signal number and frame
  • create a function exitHandler which accepts the signal number and framenumber as arguments
  • print a random text(acknowledgment) for exiting
  • exit using the exit() function
  • With ‘SIGINT’ (CTRL + C), we can register our signal handler.
  • ‘SIGTSTP’ (Ctrl + Z) is used to register the exit handler.
  • Loop infinite times using the while(1) which is always true
  • print the text ctrl+c
  • sleep for 3 seconds using the sleep() function in time
  • The Exit of the Program

Below is the implementation:

# Import signal module using the import keyword
import signal  
# Import time module using the import keyword
import time  
# create a function signalHandler which accepts the signal number and framenumber as arguments 
def signalHandler(signalnumb, frame):  
  #print the value of signal number and frame
    print("Signal Number:", signalnumb, " Frame: ", frame)  
# create a function exitHandler which accepts the signal number and framenumber as arguments 
def exitHandler(signalnumb, frame):
  # print a random text(acknowledgment) for exiting 
    print('Exiting!!!!')
    #exit using the exit() function
    exit(0)
 
# With 'SIGINT' (CTRL + C), we can register our signal handler.
signal.signal(signal.SIGINT, signalHandler)
 
# 'SIGTSTP' (Ctrl + Z) is used to register the exit handler.
signal.signal(signal.SIGTSTP, exitHandler)
 
# Loop infinite times using the while(1) which is always true
while 1:  
    #print the text ctrl+c
    print("Please Press Ctrl + C")
    #sleep for 3 seconds using the sleep() function in time 
    time.sleep(3)

After we execute our program, pressing Ctrl + C will take us to the signalHandler() function, because we have registered the handler with SIGINT (Ctrl + C).

Another handler, exitHandler(), exits the program when we press Ctrl + Z, which sends a SIGTSTP signal.

Output:

Please Press Ctrl + C 
Signal Number: 2 Frame: <frame at 0x7fae4a6badd0, file '<ipython-input-1-adfb4209d24a>', line 27, code <module>>
Exiting!!!

Alarm Signals

To transmit alarm signals to our code, we can utilize the SIGALARM signal.

Example

# Import signal module using the import keyword
import signal  
# Import time module using the import keyword
import time  
# create a function alarmhandler which accepts the signal number and framenumber as arguments 
def alarmhandler(signalnumb, frame):  
    # print the alarm time using the ctime() function in time module
    print('The Alarm Time is:', time.ctime())  
 
# Initiate our handler of the alarm signal
signal.signal(signal.SIGALRM, alarmhandler)
# After 3 seconds, set the alarm by passing 3 as an argument to the alarm() function.
signal.alarm(3) 
# Print the current Time using the ctime() function in time module
print('The current Time is:', time.ctime())  
# sleep for 3 seconds using the sleep() function in time 
time.sleep(3)

Output:

The current Time is: Fri Dec 31 16:41:52 2021
The Alarm Time is: Fri Dec 31 16:41:55 2021

In the final line, we sleep for 3 seconds to allow the alarm signal to reach our program. Otherwise, the signal would not be received because the program would have ended.