How can I send a signal from a python program?

user192082107 picture user192082107 · Feb 26, 2013 · Viewed 44.8k times · Source

I have this code which listens to USR1 signals

import signal
import os
import time

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

signal.signal(signal.SIGUSR1, receive_signal)
signal.signal(signal.SIGUSR2, receive_signal)

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

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

This works when I send signals with kill -USR1 pid

But how can I send the same signal from within the above python script so that after 10 seconds it automatically sends USR1 and also receives it , without me having to open two terminals to check it?

Answer

moomima picture moomima · Jan 7, 2014

You can use os.kill():

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

Put this anywhere in your code that you want to send the signal from.