Skip to content
Merged
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
Process.Unix: while reaping all processes, handle encountering direct…
… children.

The process that runs as pid 1 is responsible for reaping orphaned processes.
Since .NET 7, .NET applications running as pid 1 assume this responsibility.

The code meant for reaping orphaned processes didn't account for encountering
direct children. These child processes get reaped without updating
the internal state. When the code later tries to reap such a child process
it causes a FailFast because the process is missing.
  • Loading branch information
tmds committed Dec 19, 2022
commit be7ecd5747d5ae0d5036e0add46488f7ea54679b
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,24 @@ private Task WaitForExitAsync(CancellationToken cancellationToken = default)
}, cancellationToken);
}

private void ChildReaped(int exitCode, bool configureConsole)
{
lock (_gate)
{
Debug.Assert(!_exited);

_exitCode = exitCode;

if (_usesTerminal)
{
// Update terminal settings before calling SetExited.
Process.ConfigureTerminalForChildProcesses(-1, configureConsole);
}

SetExited();
}
}

private bool TryReapChild(bool configureConsole)
{
lock (_gate)
Expand All @@ -566,16 +584,7 @@ private bool TryReapChild(bool configureConsole)

if (waitResult == _processId)
{
_exitCode = exitCode;

if (_usesTerminal)
{
// Update terminal settings before calling SetExited.
Process.ConfigureTerminalForChildProcesses(-1, configureConsole);
}

SetExited();

ChildReaped(exitCode, configureConsole);
return true;
}
else if (waitResult == 0)
Expand Down Expand Up @@ -636,7 +645,7 @@ internal static void CheckChildren(bool reapAll, bool configureConsole)
}
} while (pid > 0);

if (checkAll)
if (checkAll && !reapAll)
{
// We track things to unref so we don't invalidate our iterator by changing s_childProcessWaitStates.
ProcessWaitState? firstToRemove = null;
Expand Down Expand Up @@ -675,8 +684,20 @@ internal static void CheckChildren(bool reapAll, bool configureConsole)
{
do
{
pid = Interop.Sys.WaitPidExitedNoHang(-1, out _);
} while (pid > 0);
int exitCode;
pid = Interop.Sys.WaitPidExitedNoHang(-1, out exitCode);
if (pid <= 0)
{
break;
}

// Check if the process is a child that has just terminated.
if (s_childProcessWaitStates.TryGetValue(pid, out ProcessWaitState? pws))
{
pws.ChildReaped(exitCode, configureConsole);
pws.ReleaseRef();
}
} while (true);
}
}
}
Expand Down