Created
March 26, 2026 17:29
-
-
Save dhermes/6716479576cc95e171d099ac22e51467 to your computer and use it in GitHub Desktop.
[2026-03-26] Example for SIGTERM handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| import signal | |
| import sys | |
| import time | |
| import types | |
| class _Global: | |
| SHUTDOWN_REQUESTED = False | |
| def _handle_sigterm(signum: int, frame: types.FrameType) -> None: | |
| if signum == signal.SIGTERM: | |
| print("\n:: received SIGTERM") | |
| elif signum == signal.SIGINT: | |
| print("\n:: received SIGINT") | |
| else: | |
| print(f"\n:: received Signal({signum})") | |
| if _Global.SHUTDOWN_REQUESTED: | |
| print("\nForced shutdown") | |
| sys.exit(1) | |
| _Global.SHUTDOWN_REQUESTED = True | |
| print("\nGraceful shutdown requested. Send signal again to force") | |
| signal.signal(signal.SIGTERM, _handle_sigterm) # 15 on macOS + Linux (default signal) | |
| signal.signal(signal.SIGINT, _handle_sigterm) # Ctrl-C (2 on macOS + Linux) | |
| # signal.SIGKILL: 9 on macOS + Linux | |
| # signal.SIGUSR1: 30 on macOS / 10 on Linux | |
| # signal.SIGUSR2: 31 on macOS / 12 on Linux | |
| # signal.SIGBUS: 10 on macOS / 7 on Linux | |
| def main() -> None: | |
| print(f"Running... (PID: {os.getpid()})") | |
| while not _Global.SHUTDOWN_REQUESTED: | |
| time.sleep(5.0) | |
| print("Cleaning up (for 10 seconds) ...") | |
| time.sleep(10.0) | |
| print("Done cleaning up") | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment