diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py index 514e781330..20842f6953 100644 --- a/scripts/run_semantic_tests.py +++ b/scripts/run_semantic_tests.py @@ -59,7 +59,7 @@ def _unregister_process(proc): def _kill_process_tree(proc): if proc is None: return - if os.name == "nt": + if os.name == "nt" and proc.poll() is None: try: subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) @@ -74,11 +74,13 @@ def _kill_process_tree(proc): def _terminate_active_processes(): with _processes_lock: procs = list(_active_processes) - for p in procs: - try: - p.terminate() - except OSError: - pass + if os.name != "nt": + for p in procs: + try: + p.terminate() + except OSError: + pass + # On Windows taskkill /T needs the root process alive to find its descendants. for p in procs: _kill_process_tree(p) try: diff --git a/tests/test_run_semantic_tests.py b/tests/test_run_semantic_tests.py index 7fc75e3722..eb24a402d9 100644 --- a/tests/test_run_semantic_tests.py +++ b/tests/test_run_semantic_tests.py @@ -374,6 +374,28 @@ def test_terminate_active_processes_kills_registered_processes(self): p.kill() except OSError: pass + r._unregister_process(p) + + @unittest.skipUnless(os.name == "nt", "requires Windows taskkill") + def test_windows_cancellation_stops_descendants(self): + marker = "descendant completed" + child = f"import time; time.sleep(3); print({marker!r}, flush=True)" + parent = ( + "import subprocess, sys, time\n" + f"subprocess.Popen([sys.executable, '-c', {child!r}])\n" + "print('ready', flush=True)\n" + "time.sleep(5)\n" + ) + cmd = [sys.executable, "-c", parent] + with subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True) as proc: + self.assertEqual(proc.stdout.readline().strip(), "ready") + r._register_process(proc) + try: + r._terminate_active_processes() + output, _ = proc.communicate(timeout=5) + finally: + r._unregister_process(proc) + self.assertNotIn(marker, output) @unittest.skipUnless(os.name == "posix", "POSIX process-group SIGINT test") def test_posix_sigint_cancels_queued_modules_and_stops_runner(self):