Skip to content

Let Process.Run methods kill the entire process tree on timeout or cancellation - #136513

Open
adamsitnik wants to merge 23 commits into
dotnet:mainfrom
adamsitnik:process-run-kill-entire-tree
Open

adamsitnik wants to merge 23 commits into
dotnet:mainfrom
adamsitnik:process-run-kill-entire-tree

Conversation

@adamsitnik

@adamsitnik adamsitnik commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

Summary

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.

namespace System.Diagnostics
{
    public class ProcessStartInfo
    {
        public bool? KillTreeOnRunCancellation { get; set; }
    }
}
  • 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).

Unix targets were compiled but not executed.

Resolves #136466

Note

This description was updated with GitHub Copilot.

adamsitnik and others added 4 commits October 27, 2026 13:06
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
Co-authored-by: Copilot <[email protected]>

Copilot-Session: 7ded16ff-274e-41d3-b9ec-2bb8643062c7
@azure-pipelines

azure-pipelines Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
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.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-diagnostics-process
See info in area-owners.md if you want to be subscribed.

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.

🟡 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.

3 open issues
What changed in this PR

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.
File Description
src/​libraries/​System.Diagnostics.Process/​tests/​RunTests.cs Adds tree-cleanup and stream-redirection validation tests.
src/​libraries/​System.Diagnostics.Process/​tests/​ProcessTests.cs Tests tree termination through GetProcessById.
src/​libraries/​System.Diagnostics.Process/​src/​System/​Diagnostics/​Process.Scenarios.cs Implements tree-aware timeout and cancellation cleanup; updates documentation.
src/​libraries/​System.Diagnostics.Process/​src/​Microsoft/​Win32/​SafeHandles/​SafeProcessHandle.Windows.cs Makes cancellation state internally accessible on Windows.
src/​libraries/​System.Diagnostics.Process/​src/​Microsoft/​Win32/​SafeHandles/​SafeProcessHandle.Unix.cs Makes cancellation state internally accessible on Unix.

Review effort: Balanced

@adamsitnik
adamsitnik requested a balanced review from Copilot October 28, 2026 09:53
@adamsitnik adamsitnik added this to the 12.0.0 milestone Oct 28, 2026

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.

🟡 Changes recommended

Cleanup failures can mask original capture exceptions, and descendant-cleanup tests omit synchronous timeouts, post-EOF exit waits, and filename overloads.

2 open issues
3 resolved since last review

Review effort: Balanced

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.

🔵 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

Medium severity Track launched descendants after Unix root process exits

src/​libraries/​System.Diagnostics.Process/​src/​System/​Diagnostics/​Process.Scenarios.cs:421

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.

2 resolved since last review

Review effort: Balanced

@adamsitnik

Copy link
Copy Markdown
Member Author

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 ;(

@adamsitnik
adamsitnik requested a review from jkotas October 29, 2026 17:02
@adamsitnik
adamsitnik requested a review from jkotas October 29, 2026 18:18
{
try
{
Kill(entireProcessTree: true);

@jkotas jkotas Oct 30, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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?

@adamsitnik adamsitnik Oct 30, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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:

image

@jkotas which leads me to a conclusion that this most likely should be controlled via a new, optional bool parameter:

ProcessExitStatus> RunAsync(
    string fileName, IEnumerable<string>? arguments = null,
    bool silent = false,
+   bool entireProcessTree = false,
    CancellationToken ct = default)

@jkotas jkotas Oct 30, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

which leads me to a conclusion that this most likely should be controlled via a new, optional bool parameter:

Yes, it sounds like that to me as well. It is unfortunate that we have made silent a bool - it would be nicer if it is an enum.

If we do this, we should look at trimming the implementation to be leaner.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is the job hierarchy same as process tree hiearchy?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Should the argument name be different when it is not the same?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Should the argument name be different when it is not the same?

I will bring this up during the API review tomorrow. I just don't have a better name right now.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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.)

adamsitnik and others added 3 commits November 9, 2026 14:15
Preserve existing signatures and root-only termination behavior, add required entireProcessTree overloads, and update tests and callers.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: 711d8e26-5d17-4e03-8594-700f47d29624
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
@adamsitnik
adamsitnik disabled auto-merge November 9, 2026 20:57
@adamsitnik
adamsitnik marked this pull request as draft November 9, 2026 20:57
@adamsitnik adamsitnik added the NO-MERGE The PR is not ready for merge yet (see discussion for detailed reasons) label Nov 9, 2026
This reverts commit 583917c.

# Conflicts:
#	src/tests/Common/XUnitLogChecker/XUnitLogChecker.cs
#	src/tests/run.cs
@adamsitnik 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
…n is not set

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
Co-authored-by: Copilot <[email protected]>

Copilot-Session: 711d8e26-5d17-4e03-8594-700f47d29624
@adamsitnik
adamsitnik marked this pull request as ready for review November 17, 2026 21:16
@adamsitnik adamsitnik removed the NO-MERGE The PR is not ready for merge yet (see discussion for detailed reasons) label Nov 17, 2026
{
public SafeJobHandle() : base(true) { }

internal static unsafe SafeJobHandle Create(uint limitFlags)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I do not think we should be using jobs to this. Jobs are not the same thing as process trees.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I do not think we should be using jobs to this. Jobs are not the same thing as process trees.

Could you please provide an example of a scenario that worries you?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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 branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Let Process.Run* kill the entire process tree on timeout or cancellation

3 participants