Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: frame parameter of signal handler

Tags:

python

signals

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

like image 613
user1077071 Avatar asked Sep 09 '13 18:09

user1077071


People also ask

What is frame in Python signal handler?

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.

How do you use a signal handler in Python?

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.

What is Sig_dfl?

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.

How do you increase signal in Python?

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.


1 Answers

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)
like image 138
Christian Heimes Avatar answered Oct 26 '22 20:10

Christian Heimes