From 9df2e6b72e19de00c32038cf98d19bdbaa78da78 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Tue, 13 Oct 2026 13:09:48 +0000 Subject: [PATCH 1/2] Backport Unix process reaping and descendant-first tree termination to .NET 10 Co-authored-by: adamsitnik <6011991+adamsitnik@users.noreply.github.com> --- .../src/System/Diagnostics/Process.Unix.cs | 86 +++++++++++++++---- .../Diagnostics/ProcessWaitState.Unix.cs | 16 ++-- .../tests/ProcessTests.Unix.cs | 58 +++++++++++++ .../System.Diagnostics.Process.Tests.csproj | 2 + src/native/libs/System.Native/pal_signal.c | 4 +- 5 files changed, 138 insertions(+), 28 deletions(-) diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs index 2dde9eb778cdc9..16ad7914686fbd 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs @@ -99,12 +99,68 @@ private bool GetHasExited(bool refresh) } private void KillTree(ref List? exceptions) + { + // First, stop and collect the entire process tree before killing any process. + // This is necessary because killing a parent process may cause children with + // PR_SET_PDEATHSIG to be killed by the kernel immediately, making it impossible + // to discover their descendants afterward. + List stoppedProcesses = []; + try + { + StopTree(ref exceptions, stoppedProcesses); + } + catch (Exception ex) + { + (exceptions ??= new List()).Add(ex); + } + finally + { + // Kill all stopped processes even if StopTree threw partway through. + // stoppedProcesses is in depth-first pre-order, so walking it backwards kills + // descendants before their ancestors. Killing a parent first would reparent its + // still-stopped children. When a reparented process exits, macOS can orphan the + // process group without correctly accounting for the reparenting. If the group + // still has stopped members, the kernel then sends SIGHUP and SIGCONT to every + // process in it, including unrelated processes that share the group (such as the + // caller and its ancestors). + for (int i = stoppedProcesses.Count - 1; i >= 0; i--) + { + Process process = stoppedProcesses[i]; + int killResult = Interop.Sys.Kill(process._processId, Interop.Sys.Signals.SIGKILL); + if (killResult != 0) + { + Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); + // Ignore 'process no longer exists' error. + if (errorInfo.Error != Interop.Error.ESRCH) + { + (exceptions ??= new List()).Add(new Win32Exception(errorInfo.RawErrno)); + } + } + + if (process != this) + { + process.Dispose(); + } + } + } + } + + /// + /// Recursively stops all processes in the tree (depth-first) and collects them into a flat list. + /// Stopping (SIGSTOP) before enumerating children ensures we can discover the entire tree + /// before any kill signals cause cascading terminations. + /// + /// + /// if the process was successfully stopped and added to + /// ; if the process had already + /// exited or could not be stopped, in which case the caller is responsible for disposing it. + /// + private bool StopTree(ref List? exceptions, List stoppedProcesses) { // If the process has exited, we can no longer determine its children. - // If we know the process has exited, stop already. if (GetHasExited(refresh: false)) { - return; + return false; } // Stop the process, so it won't start additional children. @@ -112,33 +168,27 @@ private void KillTree(ref List? exceptions) int stopResult = Interop.Sys.Kill(_processId, Interop.Sys.Signals.SIGSTOP); if (stopResult != 0) { - Interop.Error error = Interop.Sys.GetLastError(); + Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); // Ignore 'process no longer exists' error. - if (error != Interop.Error.ESRCH) + if (errorInfo.Error != Interop.Error.ESRCH) { - (exceptions ??= new List()).Add(new Win32Exception()); + (exceptions ??= new List()).Add(new Win32Exception(errorInfo.RawErrno)); } - return; + return false; } - List children = GetChildProcesses(); + stoppedProcesses.Add(this); - int killResult = Interop.Sys.Kill(_processId, Interop.Sys.Signals.SIGKILL); - if (killResult != 0) + List children = GetChildProcesses(); + foreach (Process childProcess in children) { - Interop.Error error = Interop.Sys.GetLastError(); - // Ignore 'process no longer exists' error. - if (error != Interop.Error.ESRCH) + if (!childProcess.StopTree(ref exceptions, stoppedProcesses)) { - (exceptions ??= new List()).Add(new Win32Exception()); + childProcess.Dispose(); } } - foreach (Process childProcess in children) - { - childProcess.KillTree(ref exceptions); - childProcess.Dispose(); - } + return true; } /// Discards any information about the associated process. diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs index 042a95b1950c64..0a66c1998def06 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs @@ -605,18 +605,18 @@ internal static void CheckChildren(bool reapAll, bool configureConsole) pid = Interop.Sys.WaitIdAnyExitedNoHangNoWait(); if (pid > 0) { - if (s_childProcessWaitStates.TryGetValue(pid, out ProcessWaitState? pws)) + if (s_childProcessWaitStates.TryGetValue(pid, out ProcessWaitState? pws) && + pws.TryReapChild(configureConsole)) { - // Known Process. - if (pws.TryReapChild(configureConsole)) - { - pws.ReleaseRef(); - } + pws.ReleaseRef(); } else { - // unlikely: This is not a managed Process, so we are not responsible for reaping. - // Fall back to checking all Processes. + // The child may be unmanaged, or stopped rather than exited. On macOS, + // waitid can report stopped children despite omitting WSTOPPED; + // the SIGCHLD handler is also registered with SA_NOCLDSTOP. + // Scan all managed children instead of repeatedly observing + // the same child without reaping it. checkAll = true; break; } diff --git a/src/libraries/System.Diagnostics.Process/tests/ProcessTests.Unix.cs b/src/libraries/System.Diagnostics.Process/tests/ProcessTests.Unix.cs index a02cc15c3a6626..3f70897db386da 100644 --- a/src/libraries/System.Diagnostics.Process/tests/ProcessTests.Unix.cs +++ b/src/libraries/System.Diagnostics.Process/tests/ProcessTests.Unix.cs @@ -714,6 +714,64 @@ public async Task TestChildProcessCleanupAfterDispose(bool shortProcess, bool en Assert.True(processReaped); } + [ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] + [PlatformSpecific(TestPlatforms.OSX)] + [InlineData(false)] + [InlineData(true)] + public void WaitForExit_StoppedChild_DoesNotPreventReapingOtherChildren(bool useAsync) + { + RemoteExecutor.Invoke(async useAsyncString => + { + const uint StoppedProcessStatus = 4; // SSTOP in sys/proc.h. + const int StopSignal = 17; // SIGSTOP on macOS. + using Process stopped = Process.Start("/bin/sleep", "300"); + using Process exiting = Process.Start("/bin/sleep", "300"); + int stoppedPid = stopped.Id; + int exitingPid = exiting.Id; + using ManualResetEventSlim sigChildReceived = new(); + using PosixSignalRegistration registration = PosixSignalRegistration.Create(PosixSignal.SIGCHLD, context => + { + context.Cancel = true; + sigChildReceived.Set(); + }); + + try + { + Assert.Equal(0, kill(stoppedPid, StopSignal)); + + Assert.True(SpinWait.SpinUntil( + () => Interop.libproc.GetProcessInfoById(stoppedPid) is { } info && + info.pbsd.pbi_status == StoppedProcessStatus, WaitInMS)); + + sigChildReceived.Reset(); + Assert.Equal(0, kill(Environment.ProcessId, Interop.Sys.GetPlatformSignalNumber(PosixSignal.SIGCHLD))); + Assert.True(sigChildReceived.Wait(WaitInMS)); + + Assert.Equal(0, kill(exitingPid, SIGKILL)); + if (bool.Parse(useAsyncString)) + { + using CancellationTokenSource cts = new(WaitInMS); + await exiting.WaitForExitAsync(cts.Token); + } + else + { + Assert.True(exiting.WaitForExit(WaitInMS)); + } + Assert.True(exiting.HasExited); + } + finally + { + // Bypass managed process locks so cleanup also works if the reaper is stuck. + Assert.Equal(0, kill(stoppedPid, SIGKILL)); + Assert.True(stopped.WaitForExit(WaitInMS)); + exiting.Kill(); + Assert.True(exiting.WaitForExit(WaitInMS)); + } + + return RemoteExecutor.SuccessExitCode; + }, useAsync.ToString()).Dispose(); + } + private static Process CreateShortProcess() { Process process = new Process(); diff --git a/src/libraries/System.Diagnostics.Process/tests/System.Diagnostics.Process.Tests.csproj b/src/libraries/System.Diagnostics.Process/tests/System.Diagnostics.Process.Tests.csproj index 718bddd017ea89..f0e6c589a17bb0 100644 --- a/src/libraries/System.Diagnostics.Process/tests/System.Diagnostics.Process.Tests.csproj +++ b/src/libraries/System.Diagnostics.Process/tests/System.Diagnostics.Process.Tests.csproj @@ -67,6 +67,8 @@ Link="Common\Interop\OSX\Interop.Libraries.cs" /> + Date: Tue, 13 Oct 2026 16:45:28 +0200 Subject: [PATCH 2/2] Apply suggestion from @adamsitnik --- .../src/System/Diagnostics/Process.Unix.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs index 16ad7914686fbd..e312a13d047939 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs @@ -102,8 +102,6 @@ private void KillTree(ref List? exceptions) { // First, stop and collect the entire process tree before killing any process. // This is necessary because killing a parent process may cause children with - // PR_SET_PDEATHSIG to be killed by the kernel immediately, making it impossible - // to discover their descendants afterward. List stoppedProcesses = []; try {