-
-
Save sils/f7d194f0285b027f3416 to your computer and use it in GitHub Desktop.
How to interrupt a process correctly in windows so catch and finally get executed.
This file contains 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
from multiprocessing import Process, Queue | |
from time import sleep | |
import ctypes | |
# WINDOWS ONLY!!! | |
def interrupt_process(pid): | |
CTRL_C_EVENT = 0x0 | |
ctypes.windll.kernel32.GenerateConsoleCtrlEvent(CTRL_C_EVENT, pid) | |
# DON'T USE THIS!!! THIS WON'T WORK AND GENERATES A COMPLETELY DIFFERENT | |
# SIGNAL NOT RECOGNIZED FROM PYTHON AS KEYBOARDINTERRUPT!!! | |
#os.kill(pid, signal.CTRL_C_EVENT) | |
def compute_fibonacci(step, q): | |
try: | |
a = 1 | |
b = 1 | |
for i in range(step): | |
print("COMPUTING...") | |
c = a | |
a += b | |
b = c | |
sleep(0.5) | |
print("RESULT STORED") | |
q.put(a) | |
except: | |
print("### ABORTED ###") | |
finally: | |
print("### FINALLY EXECUTED ###") | |
if __name__ == "__main__": | |
print("INITIALIZING") | |
q = Queue() | |
thread = Process(target=compute_fibonacci, args=(10, q)) | |
print("STARTING...") | |
thread.start() | |
print("STARTED") | |
# Interrupt the process. | |
sleep(2) | |
try: | |
interrupt_process(thread.pid) | |
# The interrupt will interrupt the whole process group including this process, | |
# we need to wait for the interrupt. | |
sleep(1) | |
# Interrupt didn't happen, something did go completely wrong! | |
exit(1) | |
except KeyboardInterrupt: | |
print("COMPUTATION TERMINATED WITH CTRL_C_EVENT!!!") | |
thread.join() | |
print("COMPUTATION ENDED") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment