Skip to content

Commit

Permalink
Process.Unix: while reaping all processes, handle encountering direct…
Browse files Browse the repository at this point in the history
… children. (#80433)

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.

Co-authored-by: Tom Deseyn <tom.deseyn@gmail.com>
  • Loading branch information
github-actions[bot] and tmds authored Jan 12, 2023
1 parent b84e2f6 commit a8e690e
Showing 1 changed file with 34 additions and 13 deletions.
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

0 comments on commit a8e690e

Please sign in to comment.