Skip to content

Kill process tree descendants before ancestors on Unix - #135624

Merged
adamsitnik merged 1 commit into
dotnet:mainfrom
thomhurst:fix-killtree-orphaned-pgrp
Oct 13, 2026
Merged

adamsitnik merged 1 commit into
dotnet:mainfrom
thomhurst:fix-killtree-orphaned-pgrp

Conversation

@thomhurst

@thomhurst thomhurst commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #131944

Problem

Process.Kill(entireProcessTree: true) on Unix first sends SIGSTOP to the whole tree, then sends SIGKILL in depth-first pre-order. Each parent is therefore killed while its children are still stopped.

On macOS this can signal unrelated processes:

  1. The parent exits and its still-stopped children are reparented to launchd.
  2. XNU tracks orphaned process groups with a per-group pg_jobc counter. fixjobc() adjusts it when a process enters or leaves a group, but reparenting does not adjust it.
  3. When a reparented process exits, fixjobc() sees a parent (launchd) in a different group of the same session and decrements pg_jobc. It can reach 0 even though the group is not really orphaned.
  4. orphanpg() then finds stopped members (the rest of the tree that has not been killed yet) and sends SIGHUP and SIGCONT to every process in the group.

By default, child processes share the caller's process group. On GitHub-hosted macOS runners that group also holds start_hca.sh, hosted-compute-agent, Runner.Listener and Runner.Worker. They receive SIGHUP, SIGCONT and SIGTERM and die, and the job ends with "The hosted runner lost communication with the server". Captures (signal logs, process tables taken before and after, spindump) are in #131944 (comment) and actions/runner-images#14833. Running the repro in its own session (setsid) avoids it, and so does killing each descendant from a snapshot without SIGSTOP. This matches the orphaned-process-group behavior. The old single-pass KillTree (.NET 10) has the same parent-first ordering and is affected too.

Fix

Walk the collected list in reverse, so that descendants are killed before their ancestors. Sending SIGKILL clears a process's stopped state right away. When an ancestor exits and its children are reparented, the children are therefore no longer stopped. In the reported repro (sh -c "sleep 60 & sleep 60; wait"), the root is killed last, so no process is still stopped when a reparented process exits.

Killing children first is also fine for the KillOnParentExit (PR_SET_PDEATHSIG) case that the two-phase stop/kill was added for, because the whole tree is still collected before any process is killed.

Remaining risk

  • If a killed child exits more slowly than its killed parent, it is still reparented. If it then exits while part of the tree is still stopped, the signal can still fire. This race is narrow.
  • An unrelated process that was reparented earlier and exits in the same process group while a KillTree call has processes stopped can still trigger it. Fully removing this would mean not using SIGSTOP on macOS, which would bring back the fork race the stop protects against.

Testing

No new test. Reproducing this needs a process group that shares a session with launchd, as on the hosted runners. That setup cannot be created from a test, and Linux computes orphaned groups correctly. The existing kill-tree and KillOnParentExit tests still cover the behavior.

Process.Kill(entireProcessTree: true) stops the whole tree with SIGSTOP and
then sends SIGKILL in depth-first pre-order, so each parent dies before its
still-stopped children. Those children are reparented to launchd. XNU does
not adjust pg_jobc on reparenting, so when a reparented process exits the
group can be treated as orphaned. orphanpg() then sends SIGHUP and SIGCONT
to every member of the group because it still has stopped members. On
GitHub-hosted macOS runners the caller shares its process group with the
runner agent, which is killed as a result.

Kill the collected processes in reverse order so that descendants are
killed (and no longer stopped) before their ancestors exit.

Fixes dotnet#131944
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Oct 12, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
13 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.

@jkotas
jkotas requested review from adamsitnik and a balanced review from Copilot October 12, 2026 22:58

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

The small code change depends on subtle macOS kernel process-group semantics and lacks a direct regression test.

0 open findings

What changed in this PR

Changes Unix process-tree termination to reduce macOS orphaned-process-group signaling.

Changes:

  • Kills stopped processes in reverse preorder, ensuring descendants are signaled before ancestors.
  • Documents the macOS process-group rationale.
File Description
Process.Unix.cs Reorders Unix tree termination and explains the platform-specific behavior.

🧠 Review effort: Balanced

@adamsitnik adamsitnik left a comment

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 change is very simple and reasonable, thank you for providing it @thomhurst !

@adamsitnik
adamsitnik merged commit f051945 into dotnet:main Oct 13, 2026
99 checks passed
@adamsitnik adamsitnik added this to the 12.0.0 milestone Oct 13, 2026
ViveliDuCh pushed a commit that referenced this pull request Oct 14, 2026
…35409)

Backport of #135323 and #135624 to
release/11.0

/cc @adamsitnik @steveisok

## Customer Impact

- [x] Customer reported
- [x] Found internally

Initially reported by the SDK
(#131944), but other customers
have experienced it as well
(#131944 (comment)).

When user calls `Process.Kill(entireProcessTree: true)` on macOS, the
application can hang.

## Regression

The changes we have made in
#128598 have surfaced a macOS bug
we were not aware of.
It's a bug in the OS itself that other frameworks need to workaround as
well (python/cpython#158962).

Full details are explained
[here](#135323 (comment))
and
[here](#135624 (comment)).

## Testing

Failing test was added and it's now passing.

## Risk

Low. When we can't reap given process (because it was stopped, not
killed) we fall back to checking individual processes rather than keep
trying forever.

fixes #131944

---------

Co-authored-by: Steve Pfister <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Tom Longhurst <[email protected]>
RLittlesII added a commit to RLittlesII/specht that referenced this pull request Nov 10, 2026
…he build job to 45 minutes (#820)

* task(0430): take the net11.0 process-run test stall

Delivers 0430

Takes the bug item: the SystemProcessRun integration tests stall the
net11.0 Integration Test step (#792 runs 42526206109, 42530364175).
Preserves 0132-F3 B-017.

* test(0430): poll a file for the cancelled run's pids and bound every process-run test

Delivers 0430

The cancel test no longer makes a FIFO with mkfifo or opens it on a
thread-pool thread. The shell writes its pid and the background sleep's
pid to a temporary name and moves it into place, and the test polls for
that file after the run starts, bounded by the test's token and a
10-second deadline. The wait for both programs to exit shares one
10-second deadline inside the 30-second test timeout, survivors are
killed, and the temporary directory is deleted in a finally block that
also cancels the run.

The write test and the missing-program test take the same 30-second
Timeout as the others, so a start that never returns fails that test
instead of stalling the step.

No .feature change needed: test-only change; the same behaviour of
SystemProcessRun is asserted.
Constraints preserved: 0132-F3 B-017

* fix(0430): kill a cancelled run's descendants first, without stopping the tree, on Unix

Delivers 0430

Preserves 0132-F3 B-017: a cancelled run still throws
OperationCanceledException and leaves no program alive.

On .NET 11 under Unix, Process.Kill(entireProcessTree: true) stops the
whole tree with SIGSTOP before it kills it (dotnet/runtime#128598) and can
stop between the two, leaving the program stopped, the host spinning and
every later Process.Start blocked. The reorder upstream
(dotnet/runtime#135624) is in the 12.0.0 milestone.

On macOS and Linux SystemProcessRun now takes one snapshot of the
program's descendants, breadth first, and sends each SIGKILL through
Process.Kill(), descendants before ancestors, then the program; nothing is
stopped first. Children come from proc_listchildpids on macOS and from one
scan of /proc/<pid>/stat on Linux, with no helper process. Windows and
other systems keep Kill(entireProcessTree: true).

0132-F3 sections 6 and 7 record the design, the rejected
/proc/<pid>/task/<tid>/children, and the gap: a program forked after the
snapshot is not killed.

* docs(0430): record the tree-kill lesson and close the item

Delivers 0430

Product lesson 0001 under src/mcp/.spec/lessons/: on .NET 11 under Unix,
Process.Kill(entireProcessTree: true) stops the tree before it kills it
and can stall every later process start in the host. The specification
delta is 0132-F3 sections 6 and 7 (bb378585); no section 3 claim changed.
0132-F3 B-017 holds through the bounded cancel test.

Item 0430 records the owner's option A and the runtime finding: the test
change alone still stalled 1 of 11 runs locally; after the production
change 26 full net11.0 tier runs and more than 40 class runs passed with
no stall, measured locally, CI to be confirmed. Its out-of-scope entry
now admits the src/mcp change the cancel test showed. Status done,
closed 2026-11-08.

* docs(0430): claim what a cancelled call does and record the review

Delivers 0430

Specifies src/mcp/.spec/README.md: 0132-F3 B-040 (a call cancelled while
the program it started is running ends cancelled) and B-041 (it leaves
running no program the call started, directly or through another), split
because one claim carried two assertions. Their scenarios, Partial section 9
rows on the existing cancel test, section 5 row 20, A-7, the section 10
entry for lesson 0001 and the Tasks line. spec_status is in-review while
the round-8 sign-off row is red; the row is the spec-reviewer's, committed
as written.

Item 0430 moves to src/mcp/.issue/ with spec and claims set, the summary
and criteria rewritten for the tree-kill finding, risk 3, status
in-progress and closed null; option A is recorded as proposed by the
coordinator and selected by the owner. Lesson 0001 names B-040 and B-041.

* test(0430): pin the descendant walk and the stat parse, and wait on a watcher

Delivers 0430

Unit tests for the two seams beneath the Unix kill (0132-F3 B-041):
ProcessTreeUnitTests holds that KillOrder lists every descendant the
delegate reaches, once, the root excluded and each before its parent,
nothing for a process with no children, and asks for each process's
children once; ProcStatLineUnitTests holds that the parent is read
after the last ')' of a /proc/<pid>/stat line and that empty or cut
short text reads none. Both are red until the implementer adds
ProcessTree and ProcStatLine in Specht.Mcp.Features.PinnedTool.

The cancel integration test (B-040, B-041) waits for its file of
process ids on a FileSystemWatcher of the temporary directory,
subscribed before File.Exists is checked, within the same 10-second
deadline linked to the test token, in place of the 20 ms poll.

Section 8 states the mechanism and the unit verdict of B-040 and B-041,
the Linux gap and what the acceptance harness lacks to bind the two
scenarios, which stay unbound; section 9 names the new tests and keeps
both rows Partial.

Committed with --no-verify: the pre-commit Format target compiles the
test project, which fails with CS0246 because ProcessTree and
ProcStatLine do not exist yet. dotnet format --verify-no-changes on the
touched files, prettier --check on the specification and ./build.sh
Specht on the working tree all passed.

* fix(0430): walk the tree through ProcessTree, parse stat lines safely, and fall back to the program when the snapshot fails

Delivers 0430

Satisfies 0132-F3 B-040 (a cancelled call ends cancelled) and B-041 (it
leaves running no program it started, directly or through another).

ProcessTree.KillOrder walks breadth first over a delegate from a process
to its children, asks each process once, leaves the root out and returns
each descendant before its ancestors. ProcStatLine.Parent reads the field
after the state, after the last parenthesis, and gives none for empty or
cut-short text. ProcScan holds one /proc scan as an object, built on
ProcStatLine; macOS keeps proc_listchildpids. SystemProcessRun guards the
snapshot: any exception from making or walking it leaves the program alone
to kill, and the run still observes both reads and rethrows the
cancellation.

Section 6 and section 7 cite B-040 and B-041, describe the new types and
the guard, record the pid-reuse window as a gap for the owner, and name
option A as proposed by the coordinator and selected by the owner.

* build(0430): give the build job a 45-minute time limit

Delivers 0430

Specifies .build/ContinuousIntegration/.spec/README.md: 0055-F2 B-027 (a
build job of ci or main still running 45 minutes after it started is
cancelled, freeing its runner), its scenario, § 5 row 32, § 6, § 7, § 8,
the Missing § 9 row (CI has no tests, owner 2026-10-08), § 10 and OQ-6
for the owner's ratification of the value.

On 2026-11-09 two of the three self-hosted runners sat in hung build jobs
for 80 to 100 minutes. Normal build jobs take 11 to 27 minutes. The
GitHubActionsSteps attribute has no time-limit setting, so
ContinuousIntegrationMiddleware swaps the generated job for
TimeLimitedJob, which writes timeout-minutes after the steps.
Regenerated ci.yml and main.yml gain that one line; step order is
unchanged. Item 0430 records the request as the coordinator's.

* task(0430): close the item

Delivers 0430

Status done and closed 2026-11-09, written before the pull request opens.
The CI criterion is the pull request's own run.
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 13, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-System.Diagnostics.Process community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Process.Kill can hang indefinitely on macOS arm64

3 participants