I need to temporarily install a custom signal handler in my code. Afterwards, I need to restore control to the original signal handler. I've seen the following before in other StackOverflow answers:
# Save original signal handler
original_SIGINT_handler = signal.getsignal(signal.SIGINT)
# Install the new SIGINT handler
signal.signal(signal.SIGINT, handle_SIGINT)
# do stuff
# Return control to original signal handler
signal.signal(signal.SIGINT, original_SIGINT_handler)
However, this will not work if the original signal handler was registered from C. According to https://pymotw.com/2/signal/, if the original signal handler was registered from C, signal.getsignal(signal.SIGINT) will return None. Then, when we go to restore the signal with signal.signal(signal.SIGINT, None), the code fails with:
TypeError: signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object
How would I go about installing a temporary signal handler, if the original was defined in C to begin with?
Is it possible to "append" functionality to an existing signal handler? Given this other StackOverflow answer, I feel like there might be a hacky way to do so, since apparently Python signal handlers run after the C signal handler returns.
For more context, I'm writing a lldb Python script, and I need to temporarily capture ctrl+c while inside my script, which I'm doing by temporarily installing my own SIGINT handler. When leaving my script, I need to restore the original ctrl+c functionality, which lldb defined.