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?
8.1: Send Signal to a Thread and Wait for it using sigwait() It then waits for the list of signals (SIGTERM and SIGALRM) using sigwait() method. Once the signal is received, it retrieves the handler of the signal and executes it. Our main code starts by registering a handler with SIGTERM signal.
Python allows us to set up signal -handlers so when a particular signal arrives to our program we can have a behavior different from the default. For example when you run a program on the terminal and press Ctrl-C the default behavior is to quit the program.
You can use the functions in Python's built-in signal module to set up signal handlers in python. Specifically the signal. signal(signalnum, handler) function is used to register the handler function for signal signalnum . Show activity on this post.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With