diff --git a/doc/changes/11841.md b/doc/changes/11841.md new file mode 100644 index 00000000000..f606fe3b839 --- /dev/null +++ b/doc/changes/11841.md @@ -0,0 +1,4 @@ +- Kill all processes in the process group after the main process has + terminated; in particular this avoids background processes in cram tests to + stick around after the test finished (#11841, fixes #11820, @Alizter, + @Leonidas-from-XIV) diff --git a/src/dune_engine/scheduler.ml b/src/dune_engine/scheduler.ml index 5b64f909658..de16e5c9807 100644 --- a/src/dune_engine/scheduler.ml +++ b/src/dune_engine/scheduler.ml @@ -889,7 +889,12 @@ let wait_for_build_process t pid = ~on_cancel:(fun () -> Process_watcher.killall t.process_watcher Sys.sigkill; Fiber.return ()) - (fun () -> wait_for_process t pid) + (fun () -> + let+ r = wait_for_process t pid in + (* [kill_process_group] on Windows only kills the pid and by this + time the process should've exited anyway *) + if not Sys.win32 then kill_process_group pid Sys.sigterm; + r) in ( res , match outcome with diff --git a/test/blackbox-tests/test-cases/cram/subprocess.t b/test/blackbox-tests/test-cases/cram/subprocess.t new file mode 100644 index 00000000000..a38a0945c43 --- /dev/null +++ b/test/blackbox-tests/test-cases/cram/subprocess.t @@ -0,0 +1,29 @@ +Testing the termination of subprocesses in cram tests. We first create a dune +project with a single cram test. + + $ cat > dune-project < (lang dune 3.19) + > EOF + +We create a file for tracking the PID of a subprocess. + + $ cat > pid.txt + $ export FILE=$(realpath ./pid.txt) + +We create a cram test that spawns a subprocess and records its PID in the file +we gave before. + + $ cat > mycram.t < $ sleep 5 & + > $ echo \$! > $FILE + > EOF + +We can now run this test, which will record its PID in the file. + + $ dune build @mycram + +The test finished successfully, now we make sure that the PID was correctly +terminated. + + $ ps -p $(cat $FILE) > /dev/null || echo "Process terminated" + Process terminated