Created
August 2, 2015 22:10
-
-
Save Makman2/f6024138108d801a8ce6 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) | |
interrupt_process(thread.pid) | |
try: | |
thread.join() | |
print("COMPUTATION SUCCESSFUL, RESULT:") | |
# Important: Don't fetch the last entry of a queue if you interrupted | |
# its process since it corrupts the queue and blocks permanently (even | |
# with a specified timeout). | |
print(q.get()) | |
except KeyboardInterrupt: | |
print("COMPUTATION TERMINATED WITH CTRL_C_EVENT!!!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment