From c80208cda99749ca24f44b49f8d5b899e3570e04 Mon Sep 17 00:00:00 2001 From: Jeff Date: Thu, 4 Nov 2021 08:59:13 -0700 Subject: [PATCH] Terminate madmax/bladebit on Windows on Ctrl-C (#9113) --- chia/plotters/plotters_util.py | 45 ++++++++++++++++++++++++---------- 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/chia/plotters/plotters_util.py b/chia/plotters/plotters_util.py index 0d6e2bd051e7..3a930103128b 100644 --- a/chia/plotters/plotters_util.py +++ b/chia/plotters/plotters_util.py @@ -1,5 +1,7 @@ import asyncio +import signal import subprocess +import sys # https://kevinmccarthy.org/2016/07/25/streaming-subprocess-stdin-and-stdout-with-asyncio-in-python/ @@ -21,24 +23,41 @@ def parse_stdout(out, progress): async def run_plotter(args, progress_dict): + orig_sigint_handler = signal.getsignal(signal.SIGINT) + installed_sigint_handler = False process = await asyncio.create_subprocess_exec( *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) - await asyncio.wait( - [ - _read_stream( - process.stdout, - lambda x: parse_stdout(x.decode("UTF8"), progress_dict), - ), - _read_stream( - process.stderr, - lambda x: print("STDERR: {}".format(x.decode("UTF8"))), - ), - ] - ) + def sigint_handler(signum, frame): + process.terminate() - await process.wait() + # For Windows, we'll install a SIGINT handler to catch Ctrl-C (KeyboardInterrupt isn't raised) + if sys.platform in ["win32", "cygwin"]: + signal.signal(signal.SIGINT, sigint_handler) + installed_sigint_handler = True + + try: + await asyncio.wait( + [ + _read_stream( + process.stdout, + lambda x: parse_stdout(x.decode("UTF8"), progress_dict), + ), + _read_stream( + process.stderr, + lambda x: print("STDERR: {}".format(x.decode("UTF8"))), + ), + ] + ) + + await process.wait() + except Exception as e: + print(f"Caught exception while invoking plotter: {e}") + finally: + # Restore the original SIGINT handler + if installed_sigint_handler: + signal.signal(signal.SIGINT, orig_sigint_handler) def run_command(args, exc_description, *, check=True, **kwargs) -> subprocess.CompletedProcess: