Skip to content

Fix ObjectDisposedException in UnixProcessReaper during Ctrl+C shutdown - #55121

Merged
JeremyKuhne merged 4 commits into
dotnet:mainfrom
JeremyKuhne:fix/processreaper-dispose-race-55096
Jul 2, 2026
Merged

JeremyKuhne merged 4 commits into
dotnet:mainfrom
JeremyKuhne:fix/processreaper-dispose-race-55096

Conversation

@JeremyKuhne

Copy link
Copy Markdown
Member

Fixes #55096.

Problem

On Linux/macOS, pressing Ctrl+C under dotnet watch intermittently crashed the child dotnet run process with an unhandled exception (exit 134):

Unhandled exception. System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'Microsoft.Win32.SafeHandles.SafeWaitHandle'.
   at System.Threading.WaitHandle.WaitOneNoCheck(...)
   at Microsoft.DotNet.Cli.Utils.ProcessReaper.UnixProcessReaper.HandleProcessExit(...)
   at System.AppContext.OnProcessExit(...)

This is a regression in Preview 6 (works in Preview 5), introduced by the UnixProcessReaper rewrite in commit f8c229052f ("Modernize Util Windows interop, enable Native AOT, refactor code").

Root cause

dotnet watch sends SIGTERM to dotnet run on Ctrl+C. The CLI's SIGTERM handler calls Environment.Exit, which raises AppDomain.ProcessExit -> HandleProcessExit on one thread, while the main thread disposes the ProcessReaper as the child exits. Two bugs resulted:

  1. The crash: HandleProcessExit called Mutex.WaitOne() on a Mutex that Dispose() could dispose concurrently. The mutex-ownership design has an inherent TOCTOU hole with no guard flag, so WaitOne() hit a disposed SafeWaitHandle and threw — unhandled, inside the ProcessExit callback, which aborts the process.

  2. Inverted signal logic: kill(pid, SIGTERM) != 0 (nonzero = failure) was replaced with SafeProcessHandle.Signal(SIGTERM) (true = success). The "couldn't send the signal, don't wait" early-return then fired on success, so the reaper stopped waiting for the child and stopped propagating its exit code.

Fix

  • Replace the thread-affine Mutex with a monitor lock plus a _shuttingDown guard flag. A monitor has no disposable wait handle to race on, and the flag makes a ProcessExit callback that starts after Dispose() a no-op — closing the race while preserving the original intent (Dispose waits for an in-flight ProcessExit to finish propagating the exit code).
  • Make HandleProcessExit never throw out of the ProcessExit callback: forward SIGTERM only while the child is running, handle Win32Exception/InvalidOperationException, then wait and propagate the exit code — restoring Preview 5 behavior.

Tests

Added ProcessReaperTests (Unix-only, since UnixProcessReaper is compiled only when !TARGET_WINDOWS):

  • ProcessExitCallbackAfterDisposeDoesNotThrow — deterministically reproduces the crash ordering (Dispose, then the ProcessExit callback). Throws ObjectDisposedException against the buggy code; a no-op after the fix.
  • ProcessExitCallbackRacingDisposeDoesNotThrow — stresses the Dispose vs ProcessExit race across many iterations.

Validation

  • Unix path cross-compiled clean (TargetOS=linux, net11.0); Windows build clean (net11.0 + net472); tests build and are discovered. The Unix-only tests were validated by cross-compilation and reasoning (the dev box is Windows); they run on CI.

Behavior change

On Unix Ctrl+C/SIGTERM, dotnet run again forwards SIGTERM to the child, waits for it, and propagates its exit code — restoring Preview 5 behavior that the inverted logic had removed.

On Unix, dotnet watch sends SIGTERM to dotnet run on Ctrl+C. The CLI SIGTERM handler calls Environment.Exit, which raises AppDomain.ProcessExit on one thread while the main thread disposes the ProcessReaper as the child exits. The Preview 6 refactor left HandleProcessExit calling Mutex.WaitOne on a mutex that Dispose could dispose concurrently, throwing an unhandled ObjectDisposedException (Cannot access a disposed object) that aborted the process (exit 134).

Replace the thread-affine Mutex with a monitor lock plus a _shuttingDown guard flag: a monitor has no disposable wait handle to race on, and the flag makes a ProcessExit callback that starts after Dispose a no-op. Also make HandleProcessExit never throw out of the ProcessExit callback.

The same refactor inverted the SIGTERM-forwarding condition: kill(pid, sig) returns nonzero on failure, but SafeProcessHandle.Signal returns true on success, so the do-not-wait early return fired on success and stopped waiting for the child and propagating its exit code. Restore the original behavior.

Add Unix-only regression tests that reproduce the Dispose vs ProcessExit race.

Fixes dotnet#55096
Copilot AI review requested due to automatic review settings July 2, 2026 17:40

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes an intermittent Unix (Linux/macOS) shutdown crash where AppDomain.ProcessExit could race ProcessReaper.Dispose() and throw ObjectDisposedException during Ctrl+C / SIGTERM-driven shutdowns (notably under dotnet watch), and restores correct SIGTERM-forwarding logic in the Unix reaper.

Changes:

  • Reworked UnixProcessReaper shutdown coordination to use a monitor lock plus a _shuttingDown guard to prevent concurrent disposal races and prevent exceptions from escaping the ProcessExit callback.
  • Corrected Unix SIGTERM forwarding behavior by removing the inverted success/failure logic and handling InvalidOperationException/Win32Exception within the callback.
  • Added Unix-only regression/stress tests covering Dispose() vs ProcessExit callback ordering/races.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
test/Microsoft.DotNet.Cli.Utils.Tests/ProcessReaperTests.cs Adds Unix-only regression + race stress tests to ensure the ProcessExit callback doesn’t throw when invoked after/during Dispose().
src/Cli/Microsoft.DotNet.Cli.Utils/ProcessReaper.cs Replaces the Mutex-based shutdown coordination with a lock + guard flag and fixes SIGTERM forwarding/waiting logic during ProcessExit.

Addresses PR review feedback: the .NET 9+ Lock type is the modern primitive and the lock statement uses it natively. Safe here because UnixProcessReaper only compiles for the current TFM (net11.0), never net472.
On non-Windows builds the SDK cross-compiles the net472 target too, where TARGET_WINDOWS is not defined, so UnixProcessReaper compiles for net472. System.Threading.Lock is net9+, so net472 failed with CS0246. Fall back to a plain object on net472 (the Unix reaper only runs at runtime on modern .NET anyway).
net472 only ever runs on Windows, so the Unix reaper is never relevant to it. TARGET_WINDOWS reflects the build TargetOS (and gates CsWin32), not the runtime, so it is not defined when net472 is cross-compiled on non-Windows - which is why the Unix reaper was leaking into net472. Guard the Unix reaper with !TARGET_WINDOWS && NET so it compiles only for modern .NET non-Windows targets, and have Create fall back to the base reaper for the (non-shipping) net472-on-non-Windows compile. This also lets System.Threading.Lock be used unconditionally, removing the net472 object fallback.
@JeremyKuhne
JeremyKuhne merged commit c662861 into dotnet:main Jul 2, 2026
25 checks passed
@JeremyKuhne
JeremyKuhne deleted the fix/processreaper-dispose-race-55096 branch July 2, 2026 21:22
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 11.0-preview7 milestone Jul 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Unstable][Linux/Mac] There is an error "Cannot access a disposed object." when press "Ctrl + C" to shut down the application

4 participants