Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Register existing signal handlers in simpervisor's atexit module #39

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
30 changes: 29 additions & 1 deletion simpervisor/atexitasync.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,39 @@
import sys

_handlers = []
_existing_handlers = {}

signal_handler_set = False


def add_handler(handler):
global signal_handler_set
if not signal_handler_set:
consideRatio marked this conversation as resolved.
Show resolved Hide resolved
# Add handler of SIGINT only if it is not default
_existing_sigint_handler = signal.getsignal(signal.SIGINT)
if _existing_sigint_handler.__qualname__ == "default_int_handler":
_existing_sigint_handler = None
_existing_handlers.update(
{
signal.SIGINT: _existing_sigint_handler,
}
)

# Add handler of SIGTERM only if it is not default
_existing_sigterm_handler = signal.getsignal(signal.SIGTERM)
if _existing_sigterm_handler == signal.Handlers.SIG_DFL:
_existing_sigterm_handler = None
_existing_handlers.update(
{
signal.SIGTERM: _existing_sigterm_handler,
}
)

signal.signal(signal.SIGINT, _handle_signal)
signal.signal(signal.SIGTERM, _handle_signal)
signal_handler_set = True
consideRatio marked this conversation as resolved.
Show resolved Hide resolved
_handlers.append(handler)
# print(_existing_handlers)


def remove_handler(handler):
Expand All @@ -31,4 +53,10 @@ def _handle_signal(signum, *args):
signum = signal.CTRL_C_EVENT
for handler in _handlers:
handler(signum)
sys.exit(0)
# Finally execute any existing handler that were registered in Python
# Bail if existing handler is not a callable
existing_handler = _existing_handlers.get(signum, None)
if existing_handler is not None and callable(existing_handler):
existing_handler(signum, None)
else:
sys.exit(0)