Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default signal handling in Python

Tags:

python

signals

I would like to register a custom signal handler that does some things and then continues with the normal signal handling, specifically for the SIGTERM signal.

Python does not have a SIGTERM handler registered (Python: What is the default handling of SIGTERM?), so how can I continue with the OS's normal SIGTERM processing after I do my own custom handling?

def my_handler(self, signum, frame):
    do_something()
    # What do I do here to raise to the OS?

signal.signal(signal.SIGTERM, my_handler)
like image 965
C_Z_ Avatar asked Aug 09 '26 14:08

C_Z_


1 Answers

If the fatal signal's previous disposition was the default, the best you can do is restore that disposition and re-raise the signal.

This will at least cause your process to terminate abnormally, such that its parent can tell which signal killed it (os.WIFSIGNALED). If the fatal signal has an "additional action" like a core file, this mimicry will not be perfect.

orig_handler = signal.signal(signal.SIGTERM, my_handler)

def my_handler(signum, frame):
  do_something()

  # Now do whatever we'd have done if
  # my_handler had not been installed:

  if callable(orig_handler):              # Call previous handler
    orig_handler(signum, frame)
  elif orig_handler == signal.SIG_DFL:    # Default disposition
    signal.signal(signum, signal.SIG_DFL)
    os.kill(os.getpid(), signum)
                                          # else SIG_IGN - do nothing

Re-raising the signal as above isn't nuanced enough for signals that stop the process (e.g., SIGTSTP) or are ignored by default (SIGCHLD, SIGURG).

like image 73
pilcrow Avatar answered Aug 12 '26 04:08

pilcrow