Skip to content

Commit

Permalink
avoid running exit hooks twice
Browse files Browse the repository at this point in the history
  • Loading branch information
norswap committed Jan 15, 2024
1 parent d469fdd commit a427ecf
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions exithooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,19 @@ def __init__(self):
self.hooks = []
"""List of functions to call when exiting."""

self.signal_fired = False
"""
Record when a signal has been fired to avoid calling hooks again with the atexit handler.
"""

atexit.register(self._run_hooks)
signal.signal(signal.SIGTERM, self._signal_handler)
signal.signal(signal.SIGINT, self._signal_handler)
signal.signal(signal.SIGQUIT, self._signal_handler)

def _run_hooks(self):
if self.signal_fired:
return
for hook in self.hooks:
hook(0)

Expand All @@ -42,6 +49,7 @@ def _signal_handler(self, signum, frame):
finally:
if signum == signal.SIGINT:
print("Interrupted by SIGINT (most likely Ctrl-C).")
self.signal_fired = True
exit(signum)

def register(self, hook: Callable[[int], None]):
Expand Down

0 comments on commit a427ecf

Please sign in to comment.