What is a signal?

Software interrupts sent to the program to notify on significant event or request the program  to run special sequence .

For example, the following command uses SIGHUP signal to request the program to reload it’s configuration

Anther common signal is the SIGTERM which is used to terminate the program

In the example above we used the signal number instead of ‘SIGTERM’

Next, I’ll show you how display all the signals and their numbers.

How to list all the signals?

To list all the signals on your system, you can use ‘kill -l’

As you can see it prints list of all the signals and their numbers. So if, for example, we want to used SIGKILL to kill a program, we can use it this way:

How to use signals with Python?

In Python you have the ‘signal’ module, which is part of the standard library.

Here is an example of how to catch/handle SIGTERM signal sent to your python program

First step is to import the signal module.

Next, we defined function that will handle the signal SIGTERM. First param is signum which is the signal number and the second is frame which is the  stack frame.

This is how your signal handle function signature should look like. The content of the function is up to you, in this example I simply printed a specific string.

Last line is how we set the signal handler for the signal SIGTERM

Can I define my own signals?

Yes, for this you have SIGUSR1 and SIGUSR2 which are user defined signals.