How to avoid overriding of signal handlers in Python?

Viewed 2995

My experiment code is like:

import signal

def hi(signum, frame):
    print "hi"

signal.signal(signal.SIGINT, hi)
signal.signal(signal.SIGINT, signal.SIG_IGN)

hi didn't get printed, because the signal handler is overridden by signal.SIG_IGN.

How can I avoid this?

3 Answers

Simply do the same as it would be done in C:

sig_hand_prev = None

def signal_handler(signum, frame):
  ...
  signal.signal(signum, sig_hand_prev)
  os.kill(os.getpid(), signum)

def install_handler(signum):
  global sig_hand_prev
  sig_hand_prev = signal.signal(signum, signal_handler)

The key idea here is that you save only the previous handler and raise it again when you finished your stuff. In this way the signal handling is a single linked list OOB.

Related