I was looking through the Python documentation for signal and in the example code:
def handler(signum, frame):
print 'Signal handler called with signal', signum
raise IOError("Couldn't open device!")
The 'frame' parameter is not used in the actual function. I noticed this in a lot of code on stackoverflow/online regarding signal handlers. What is the 'frame' parameter? Why is it kept in the function header?
Thank you
The frame argument is the stack frame, also known as execution frame. It point to the frame that was interrupted by the signal. The parameter is required because any thread might be interrupted by a signal, but the signal is only received in the main thread.
Python signal handlers are always executed in the main Python thread of the main interpreter, even if the signal was received in another thread. This means that signals can't be used as a means of inter-thread communication. You can use the synchronization primitives from the threading module instead.
SIG_DFL specifies the default action for the particular signal. The default actions for various kinds of signals are stated in Standard Signals. SIG_IGN. SIG_IGN specifies that the signal should be ignored.
You can use the os. kill method. Since Python 2.7 it should work (did not test it myself) on both Unix and Windows, although it needs to be called with different parameters: import os, signal os.
The frame argument is the stack frame, also known as execution frame. It point to the frame that was interrupted by the signal. The parameter is required because any thread might be interrupted by a signal, but the signal is only received in the main thread.
Example:
import signal
import os
import traceback
def handler(signum, frame):
print signum, frame
print "print stack frames:"
traceback.print_stack(frame)
def demo(n):
if n == 3:
os.kill(os.getpid(), signal.SIGUSR1)
return
demo(n+1)
signal.signal(signal.SIGUSR1, handler)
demo(1)
Output:
$ python t.py
10 <frame object at 0x1e00520>
print stack frames:
File "t.py", line 17, in <module>
demo(1)
File "t.py", line 14, in demo
demo(n+1)
File "t.py", line 14, in demo
demo(n+1)
File "t.py", line 12, in demo
os.kill(os.getpid(), signal.SIGUSR1)
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