send python signal

How to Send Signal from Python

Every OS sends signals to different processes to terminate or pause their execution, and also do other things. These signals are typically sent by OS itself or by user input also. Most scripts are also capable of receiving signals on their own or programmatically. But sometimes you may need to send signal from python. In this article, we will learn how to do this.

How to Send Signal from Python

Let us say you have the following script test.py to listen to specific signals.

#!/usr/bin/env python 

import signal
import os
import time

def receive_signal(signum, stack):
    print 'Received:', signum

signal.signal(signal.SIGUSR1, receive_signal)


print 'PID is:', os.getpid()

while True:
    print 'Waiting...'
    time.sleep(5)

When you run the above script with the following command, it will keep listening for incoming signal. Let us make it an executable.

$ sudo chmod +x test.py

Run it with the following command.

$ python test.py

Now if you send the following signal from terminal, it will kill the above process.

$ kill -USR1 pid

But if you want to send the same signal from another python script, then you need to add the following line in that script.

os.kill(os.getpid(), signal.SIGUSR1)

Here is a sample script test2.py to do the same.

#!/usr/bin/env python 

import signal
import os

os.kill(os.getpid(), signal.SIGUSR1)

Save and close the file. Make it an executable.

$ sudo chmod +x test2.py

Run it with the following command.

$ python test2.py

When you run the following command, it will terminate test.py. Similarly, you can modify your python script to send different kinds of signals.

Also read:

How to Clear Canvas for Redrawing in JS
How to Use Decimal Step for Range in Python
How to Get Browser Viewport Dimension in JS
How to Auto Resize TextArea to Fit Content
How to Render HTML in TextArea

Leave a Reply

Your email address will not be published.