Created
November 16, 2024 13:19
-
-
Save JakubDotPy/043fb38d8d9015f3613b300baf4d499f to your computer and use it in GitHub Desktop.
Create a ctrl-c catching killbox, that will "arm" on first SIGINT and kill the process on second.
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 itertools | |
import signal | |
import sys | |
import time | |
from threading import Timer | |
class Killbox: | |
def __init__(self, timeout=5): | |
self.timeout = timeout | |
self.armed = False | |
def _start_timer(self): | |
self.timer = Timer(self.timeout, self.disarm) | |
self.timer.start() | |
def arm(self): | |
self.armed = True | |
self._start_timer() | |
print("Killbox armed. Press CTRL+C again within {} seconds to terminate.".format(self.timeout)) | |
def disarm(self): | |
self.armed = False | |
print("Killbox disarmed. Press CTRL+C again to arm.") | |
def handle_sigint(self, signum, frame): | |
if self.armed: | |
print("Killbox triggered. Exiting immediately.") | |
self.timer.cancel() | |
sys.exit(1) | |
else: | |
self.arm() | |
killbox = Killbox() | |
# Attach the SIGINT handler | |
signal.signal(signal.SIGINT, killbox.handle_sigint) | |
# Dummy long-running process | |
print("Press CTRL+C to test.") | |
for num in itertools.count(): | |
try: | |
print(num) | |
time.sleep(1) | |
except KeyboardInterrupt: | |
# Handle additional KeyboardInterrupt if necessary | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment