Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -99,46 +99,94 @@ private bool GetHasExited(bool refresh)
}

private void KillTree(ref List<Exception>? 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
List<Process> stoppedProcesses = [];
try
{
StopTree(ref exceptions, stoppedProcesses);
}
catch (Exception ex)
{
(exceptions ??= new List<Exception>()).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<Exception>()).Add(new Win32Exception(errorInfo.RawErrno));
}
}

if (process != this)
{
process.Dispose();
}
}
}
}

/// <summary>
/// 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.
/// </summary>
/// <returns>
/// <see langword="true"/> if the process was successfully stopped and added to
/// <paramref name="stoppedProcesses"/>; <see langword="false"/> if the process had already
/// exited or could not be stopped, in which case the caller is responsible for disposing it.
/// </returns>
private bool StopTree(ref List<Exception>? exceptions, List<Process> 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.
// This is best effort: kill can return before the process is stopped.
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<Exception>()).Add(new Win32Exception());
(exceptions ??= new List<Exception>()).Add(new Win32Exception(errorInfo.RawErrno));
}
return;
return false;
}

List<Process> children = GetChildProcesses();
stoppedProcesses.Add(this);

int killResult = Interop.Sys.Kill(_processId, Interop.Sys.Signals.SIGKILL);
if (killResult != 0)
List<Process> 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<Exception>()).Add(new Win32Exception());
childProcess.Dispose();
}
}

foreach (Process childProcess in children)
{
childProcess.KillTree(ref exceptions);
childProcess.Dispose();
}
return true;
}

/// <summary>Discards any information about the associated process.</summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@
Link="Common\Interop\OSX\Interop.Libraries.cs" />
<Compile Include="$(CommonPath)Interop\OSX\Interop.libproc.cs"
Link="Common\Interop\OSX\Interop.libproc.cs" />
<Compile Include="$(CommonPath)Interop\OSX\Interop.libproc.GetProcessInfoById.cs"
Link="Common\Interop\OSX\Interop.libproc.GetProcessInfoById.cs" />
<Compile Include="$(CommonPath)Interop\OSX\Interop.libSystem.cs"
Link="Common\Interop\OSX\Interop.libSystem.cs" />
<Compile Include="$(CommonPath)Interop\Unix\Interop.Libraries.cs"
Expand Down
4 changes: 2 additions & 2 deletions src/native/libs/System.Native/pal_signal.c
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,7 @@ void SystemNative_SetTerminalInvalidationHandler(TerminalInvalidationCallback ca

installed = InstallSignalHandler(SIGCONT, SA_RESTART);
assert(installed);
installed = InstallSignalHandler(SIGCHLD, SA_RESTART);
installed = InstallSignalHandler(SIGCHLD, SA_RESTART | SA_NOCLDSTOP);
assert(installed);
installed = InstallSignalHandler(SIGWINCH, SA_RESTART);
assert(installed);
Expand All @@ -504,7 +504,7 @@ void SystemNative_RegisterForSigChld(SigChldCallback callback)
{
g_sigChldCallback = callback;

installed = InstallSignalHandler(SIGCHLD, SA_RESTART);
installed = InstallSignalHandler(SIGCHLD, SA_RESTART | SA_NOCLDSTOP);
assert(installed);
}
pthread_mutex_unlock(&lock);
Expand Down
Loading