You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Let Process.Run methods kill the entire process tree on timeout or cancellation - #136513
Implement the approved ProcessStartInfo.KillTreeOnRunCancellation API, which lets Process.Run* terminate the entire process tree, rather than only the started process, on timeout, cancellation, or output-capture failure.
The property is honored only by Process.Run(ProcessStartInfo, TimeSpan?), RunAsync(ProcessStartInfo, CancellationToken), RunAndCaptureText(ProcessStartInfo, TimeSpan?), and RunAndCaptureTextAsync(ProcessStartInfo, CancellationToken). Other APIs that start processes ignore it. null (the default) and false keep the existing root-only behavior. Successful completion does not terminate descendants that are still running.
On Windows, each opted-in operation creates its own job object, separate from the shared KillOnParentExit job. Regular startup assigns it atomically through PROC_THREAD_ATTRIBUTE_JOB_LIST; alternate-credential startup creates the process suspended, assigns the jobs, then resumes it. Termination uses TerminateJobObject, so the Windows implementation never references Process.Kill(bool). Explicit job breakaway is allowed (JOB_OBJECT_LIMIT_BREAKAWAY_OK) and escaped descendants are not terminated. Kill-on-job-close is not used. Job creation and assignment failures are surfaced as exceptions.
On Unix, use the existing Process.Kill(entireProcessTree: true) with a root-only fallback. Its existing limitations remain, including not finding descendants after their parent has exited.
The tree-termination paths are reachable only through static delegates assigned by the property setter (the same pattern as UseShellExecute), so apps that never set the property can trim them.
Noncapturing calls with no timeout, an infinite timeout, or a noncancelable token use the existing paths. Capturing calls use the tree path whenever the property is true, so capture failures also clean up descendants. Cleanup failures never replace the original exception.
Also fix two issues in the shared code: RunAndCaptureText treated Timeout.InfiniteTimeSpan as an already-expired deadline when waiting for exit after capture, and Run/RunAndCaptureText started the process before rejecting an invalid timeout.
Validation
On Windows x64, Release:
.\.dotnet\dotnet.exe build src\libraries\System.Diagnostics.Process\src\System.Diagnostics.Process.csproj -c Release /p:RunAnalyzersInBuild=true — passed for all configured targets, with zero warnings or errors.
.\.dotnet\dotnet.exe build /t:Test src\libraries\System.Diagnostics.Process\tests\System.Diagnostics.Process.Tests.csproj -c Release — 731 total: 728 passed, 2 skipped, 1 failed. All 80 RunTests cases passed. The sole failure, ProcessHandlesTests.ChildProcess_CanBreakAwayFromJob(killOnParentExit: False), is a pre-existing Access-denied failure in this environment, unrelated to this change.
The two new regression tests (infinite timeout after capture, invalid timeout) failed before the fix and pass with it.
NativeAOT (direct ILC compilation, Windows x64): with the property never set, the tree-termination paths and SafeJobHandle.Terminate are absent from the dependency graph; setting it to true brings them in. Neither variant references Process.Kill(bool).
Apply whole-process-tree cleanup to all Run helpers while preserving public SafeProcessHandle wait behavior. Cover both overload forms and cleanup during capture and after output closes.
Co-authored-by: Copilot <[email protected]>
Copilot-Session: 7ded16ff-274e-41d3-b9ec-2bb8643062c7
Implement tree cleanup using SafeProcessHandle and native process queries instead of calling back into Process. Share the lower-level implementation with Process.Kill and cover fetched-by-ID handles.
Co-authored-by: Copilot <[email protected]>
Copilot-Session: 7ded16ff-274e-41d3-b9ec-2bb8643062c7
Restore the original SafeProcessHandle, ProcessManager, and platform implementations. Use Process.Kill(entireProcessTree: true) for Run timeout and cancellation cleanup while retaining the regression tests and stream-redirection validation.
Co-authored-by: Copilot <[email protected]>
Copilot-Session: 7ded16ff-274e-41d3-b9ec-2bb8643062c7
Azure Pipelines:
Successfully started running 3 pipeline(s).
12 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Termination failures can leave timeout or cancellation paths waiting indefinitely, while the tests contain Debug-runtime watchdog timing errors and a scheduling-dependent capture assertion.
Updates Process.Run* to terminate descendants as well as the launched process on timeout or cancellation, using the existing process-tree termination support.
Changes:
Applies tree termination during output capture and subsequent exit waits.
Updates XML documentation and exposes cancellation state internally on both platform-specific safe handles.
Adds coverage for tree cleanup, redirected-stream rejection, and tree termination through a process retrieved by ID.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Cleanup failures can mask original capture exceptions, and descendant-cleanup tests omit synchronous timeouts, post-EOF exit waits, and filename overloads.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
On Unix, background descendants can keep redirected stdout open and survive cleanup after the shell exits because process-tree discovery skips an exited root.
No open issues 🎉
1 previously missed issue
In code that hasn't changed since last review
Track launched descendants after Unix root process exits
On Unix, a shell can exit while a background child keeps redirected stdout open, so capture remains pending until timeout or cancellation. Cleanup then leaves that child running: Process.Unix.cs:170–173 skips tree discovery for an exited root, whose children have already been reparented. To cover this case, retain a way to identify and terminate the launched descendants from startup rather than relying solely on the root PID at cleanup time.
On Unix, background descendants can keep redirected stdout open and survive cleanup after the shell exits because process-tree discovery skips an exited root.
Based on my understanding of available Unix sys-calls and mechanisms, there is nothing we can do about it ;(
The reason will be displayed to describe this comment to others. Learn more.
Kill(entireProcessTree: true) is a ton on code. This change will add about ~400kB to a simple NAOT compiled app that just starts process using the simple APIs that this PR is changing (on Windows). Is this the right tradeoff?
The reason will be displayed to describe this comment to others. Learn more.
Kill(entireProcessTree: true) is a ton on code. This change will add about ~400kB to a simple NAOT compiled app that just starts process using the simple APIs that this PR is changing (on Windows).
As of today, it is. With #126273, we could make it trivial, especially here where we know that we are about to start a process and we know whether we may need to kill entire tree or not (timeout/cancelable token was provided). This is what some of our 1P customers do (I keep an eye on code that was not able to remove all custom p/invokes after migrating to the new APIs).
Is this the right tradeoff?
We are going to increase the size on disk, but on the other hand we are going to protect some of our customers from hard to diagnose issues. I hate regressing any kind of benchmarks, but here I think it's the right thing to do. Especially since we can eliminate this regression (in a follow up PR) and make the whole operation faster and atomic (at the cost of putting all processes into a Job).
The reason will be displayed to describe this comment to others. Learn more.
This is what some of our 1P customers do
We should be also asking how many are not doing this and would be actually broken by this change. This change can cut both ways - both on functionality and/or on performance.
Are there example in other ecosystems where simple process APIs try to kill the whole process tree on failure?
The reason will be displayed to describe this comment to others. Learn more.
We should be also asking how many are not doing this and would be actually broken by this change. This change can cut both ways - both on functionality and/or on performance.
I think that 99.9% would benefit and only 0.1% could be broken for scenarios like spawning background compiler process for performance purposes.
Are there example in other ecosystems where simple process APIs try to kill the whole process tree on failure?
I've used the Office Copilot Researcher to answer your quesiton:
@jkotas which leads me to a conclusion that this most likely should be controlled via a new, optional bool parameter:
The reason will be displayed to describe this comment to others. Learn more.
Is the job hierarchy same as process tree hiearchy?
No, some processes can breakaway from the job. This is done on purpose (to let some processes outlive it on purpose). This is documented in the XML docs.
The reason will be displayed to describe this comment to others. Learn more.
The simple solution would be to call the argument killEntireProcessTreeOnTimeout and do exactly what its name says
To deal with the bloat, factor the implementation such that you will get the code bloat from this option only when you actually use it. (Also, in addition to make this opt-in - we may be able to refactor the implementation to come with less code bloat.)
Remove the four filename-based overloads and simplify their tests to match the reduced API surface.
Co-authored-by: Copilot <[email protected]>
Copilot-Session: 711d8e26-5d17-4e03-8594-700f47d29624
This reverts commit 583917c.
# Conflicts:
# src/tests/Common/XUnitLogChecker/XUnitLogChecker.cs
# src/tests/run.cs
adamsitnik
changed the title
Make Process.Run methods kill the entire process tree on timeout or cancellation
Let Process.Run methods kill the entire process tree on timeout or cancellation
Nov 10, 2026
….KillTreeOnRunCancellation
Implements the API approved in dotnet#136466.
Co-authored-by: Copilot <[email protected]>
Copilot-Session: 711d8e26-5d17-4e03-8594-700f47d29624
- Treat Timeout.InfiniteTimeSpan as no deadline when waiting for exit after output capture.
- Validate the timeout before starting the process.
- Avoid validating ProcessStartInfo twice on non-capturing paths.
- Remove leftover test changes.
Co-authored-by: Copilot <[email protected]>
Copilot-Session: 711d8e26-5d17-4e03-8594-700f47d29624
The reason will be displayed to describe this comment to others. Learn more.
For example, Windows let's you start a process outside the current process tree via PROC_THREAD_ATTRIBUTE_PARENT_PROCESS. I expect this option to be used to launch background processes that are meant to survive the current tree.
This is giving alternative meaning to what process tree means.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Implement the approved
ProcessStartInfo.KillTreeOnRunCancellationAPI, which letsProcess.Run*terminate the entire process tree, rather than only the started process, on timeout, cancellation, or output-capture failure.Process.Run(ProcessStartInfo, TimeSpan?),RunAsync(ProcessStartInfo, CancellationToken),RunAndCaptureText(ProcessStartInfo, TimeSpan?), andRunAndCaptureTextAsync(ProcessStartInfo, CancellationToken). Other APIs that start processes ignore it.null(the default) andfalsekeep the existing root-only behavior. Successful completion does not terminate descendants that are still running.KillOnParentExitjob. Regular startup assigns it atomically throughPROC_THREAD_ATTRIBUTE_JOB_LIST; alternate-credential startup creates the process suspended, assigns the jobs, then resumes it. Termination usesTerminateJobObject, so the Windows implementation never referencesProcess.Kill(bool). Explicit job breakaway is allowed (JOB_OBJECT_LIMIT_BREAKAWAY_OK) and escaped descendants are not terminated. Kill-on-job-close is not used. Job creation and assignment failures are surfaced as exceptions.Process.Kill(entireProcessTree: true)with a root-only fallback. Its existing limitations remain, including not finding descendants after their parent has exited.UseShellExecute), so apps that never set the property can trim them.true, so capture failures also clean up descendants. Cleanup failures never replace the original exception.RunAndCaptureTexttreatedTimeout.InfiniteTimeSpanas an already-expired deadline when waiting for exit after capture, andRun/RunAndCaptureTextstarted the process before rejecting an invalid timeout.Validation
On Windows x64, Release:
.\.dotnet\dotnet.exe build src\libraries\System.Diagnostics.Process\src\System.Diagnostics.Process.csproj -c Release /p:RunAnalyzersInBuild=true— passed for all configured targets, with zero warnings or errors..\.dotnet\dotnet.exe build /t:Test src\libraries\System.Diagnostics.Process\tests\System.Diagnostics.Process.Tests.csproj -c Release— 731 total: 728 passed, 2 skipped, 1 failed. All 80RunTestscases passed. The sole failure,ProcessHandlesTests.ChildProcess_CanBreakAwayFromJob(killOnParentExit: False), is a pre-existing Access-denied failure in this environment, unrelated to this change.SafeJobHandle.Terminateare absent from the dependency graph; setting it totruebrings them in. Neither variant referencesProcess.Kill(bool).Unix targets were compiled but not executed.
Resolves #136466
Note
This description was updated with GitHub Copilot.