33

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?

user192082107
  • 1,277
  • 4
  • 15
  • 19

2 Answers2

63

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.

Elias Zamaria
  • 96,623
  • 33
  • 114
  • 148
moomima
  • 1,200
  • 9
  • 12
  • 2
    This is useful for having a docker container commit seppuku – jmcgrath207 Sep 07 '20 at 23:13
  • Can you explain what `SIGUSR1` are? Is it language Constant or I should change it value according to the signal other program can receive ? – Salem Apr 21 '22 at 05:46
  • @Salem, it's actually an OS-level constant (see https://www.man7.org/linux/man-pages/man7/signal.7.html) – moomima Apr 08 '23 at 08:27
6

If you are willing to catch SIGALRM instead of SIGUSR1, try:

signal.alarm(10)

Otherwise, you'll need to start another thread:

import time, os, signal, threading
pid = os.getpid()
thread = threading.Thread(
  target=lambda: (
    time.sleep(10),
    os.kill(pid, signal.SIGUSR1)))
thread.start()

Thus, this program:

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)
signal.signal(signal.SIGALRM, receive_signal)  # <-- THIS LINE ADDED

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

signal.alarm(10)                               # <-- THIS LINE ADDED

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

produces this output:

$ python /tmp/x.py 
My PID is: 3029
Waiting...
Waiting...
Waiting...
Waiting...
Received: 14
Waiting...
Waiting...
Robᵩ
  • 163,533
  • 20
  • 239
  • 308