Skip to content

Extend the Interrupt Rule to .NET Console Apps That Run Child Tools #4507

Backlog

Description

@ptr727

Problem

CODESTYLE.md "Interrupts" covers shell and Python scripts only. Nothing states how a .NET console app handles SIGINT, SIGTERM, or SIGQUIT, so each app gets whatever its entry point happened to wire up. The fleet's .NET console apps that run child tools have drifted into three different behaviors:

App Mechanism Signals handled Children on interrupt Exit status on interrupt
PlexCleaner Its own PosixSignalRegistration in Main, synchronous ParseResult.Invoke SIGINT, SIGTERM, SIGQUIT Graceful: CliWrap's graceful token sends the child SIGINT 130, 143, or 131 returned from Main, and 1 when the race below hits
PhotoCleaner InvokeAsync with ProcessTerminationTimeout = null None Not stopped, since the process ends at once Ended by the signal, its "cancelled" path and log flush never run
AudioCleaner InvokeAsync with the default ProcessTerminationTimeout SIGINT, SIGTERM Forceful: ExecuteBufferedAsync(token) kills the child 130 or 143 after 2 seconds, even while the action is still unwinding

The PhotoCleaner and AudioCleaner rows are read from their source and from System.CommandLine's source, not from a run. The PlexCleaner row and everything below were measured in its Docker image, .NET 10.0.15 on Ubuntu, over roughly 120 interrupted runs.

What System.CommandLine Does and Does Not Do

From ProcessTerminationHandler and InvocationPipeline:

  • The handler is created only for an asynchronous action under InvokeAsync. A SynchronousCommandLineAction run through Invoke gets no termination handling at all.
  • ProcessTerminationTimeout defaults to 2 seconds. Past it, InvokeAsync returns 130 or 143 while the action is still running, so Main returns and the cleanup is abandoned.
  • ProcessTerminationTimeout = null creates no handler. The termination request is then not handled, and the process ends immediately unless the app registers its own handler.
  • SIGQUIT is not handled.

.NET 10 also no longer installs a SIGTERM handler of its own. So a docker stop ends an app with no registration immediately, with no ProcessExit and no log flush.

Findings from the Measured Runs

  1. A terminal Ctrl-C and a container stop reach different processes. Ctrl-C, Ctrl-, and Ctrl-Z on a docker run -it terminal signal the whole foreground process group. So the running child tool receives the signal at the same instant as the app. docker stop, docker kill --signal, and the signal a non-TTY docker run client proxies all reach PID 1 alone, so the app has to stop the child itself. An app tested on only one of the two paths has not shown that it handles the other. PlexCleaner's own registration handled every path below, serial and parallel, with and without --init:

    Stop Reaches Exit status Summary logged
    Ctrl-C on the terminal Process group 130 Yes
    Ctrl-\ on the terminal Process group 131 Yes
    docker stop PID 1 143 Yes
    docker kill --signal INT, QUIT, TERM PID 1 130, 131, 143 Yes
    Signal to a non-TTY docker run client PID 1, proxied 130, 143 Yes
    Ctrl-D, Ctrl-Q, Ctrl-Z on the terminal Nothing that stops the run 0 Yes, as a full run
  2. The app can see its child die before its own handler runs. .NET dispatches a PosixSignalRegistration handler asynchronously on a separate thread. On the process-group path, the child exits by the signal and the app reads that as a tool failure first. In 6 of 30 runs interrupted during startup tool verification, the app logged that the tool was not found and exited 1. The handler's "interrupted" line then appeared after the exit-code line. The exit status is decided before the handler has set it.

  3. A signal before registration ends the process with no summary. In 4 of 30 early runs the signal landed before Main registered its handlers. The runtime's default then ended the process with status 130 and no logged summary.

  4. A launcher between the caller and the app can replace the status. Under dotnet-coverage collect, 11 interrupted runs exited 0 five times, 130 five times, and 1 once. The app itself logged 130 in each. This is the same hazard the shell and Python rules already name for uv run.

  5. Ctrl-D, Ctrl-Q, and Ctrl-Z have no effect inside a container. Ctrl-D is end of input, Ctrl-Q is flow control, and SIGTSTP is ignored by PID 1. Each run finished normally with status 0. This is expected, and it is listed only because a past release documented Ctrl-Q and Ctrl-Z as stop keys.

A separate fault, an internal CLR error (0x80131506) on SIGINT during a tool run, prompted this investigation. It did not reproduce in any of the measured runs, and it is tracked in PlexCleaner's own issue rather than here.

Recommendation

Extend "Interrupts" to .NET console apps, with the mechanics in a "Interrupts in .NET" subsection packaged into the dotnet-codestyle Skill. The general bullets apply as written, release what is held, write atomically, and print one line naming the signal. The .NET mechanics would state:

  • One handling path, registered first in Main. The app registers PosixSignalRegistration for SIGINT, SIGTERM, and SIGQUIT before any other work. Each handler sets context.Cancel = true and cancels one process-wide CancellationTokenSource. That works for a synchronous and an asynchronous action alike. Where an app uses System.CommandLine's handler instead, it sets ProcessTerminationTimeout to Timeout.InfiniteTimeSpan, neither the 2-second default nor null. It still registers SIGQUIT itself.
  • A child that a signal ended is an interrupt, not a tool failure. A child exit status of 128 plus SIGINT, SIGTERM, or SIGQUIT means the stop reached the child first. The app then cancels its own token as the handler would and records that signal for the exit status. This removes the race in finding 2 without waiting on the handler thread.
  • Children are stopped gracefully and waited for. On cancellation the app asks each child to stop, such as through CliWrap's graceful cancellation token, and waits for it. Forceful cancellation follows only after a bounded wait. A container stop reaches only PID 1, so this is the only path that stops the child there.
  • An interrupted run exits 128 plus the signal number. Main returns 130, 143, or 131 after cleanup and never 0 or 1. A .NET app has no portable way to re-raise the signal. In a container it usually runs as PID 1, which a re-raised signal does not end. So the status is returned rather than re-raised, which is the deliberate difference from the script rule.
  • A .NET app that runs a child process owes a test that signals it mid-run. The test covers both delivery paths, the process group and the app alone. It asserts the exit status, that the summary is logged, and that no child remains.

The open decision is whether the .NET mechanics prefer an app's own PosixSignalRegistration or System.CommandLine's handler configured as above. The recommendation is the app's own registration. It is the only one that covers a synchronous action and SIGQUIT, and it keeps the exit status in the app's hands.

Reproducing

A constructed setup reproduces findings 1 to 3 with any media tool image. It is six synthetic one-minute AVI files made with ffmpeg -f lavfi -i testsrc2, processed under docker run -it through script. It then sends \003 to the terminal after a delay, or docker stop the container. A delay under about 2 seconds lands in startup tool verification, where finding 2 shows.

Activity

  1. added
    enhancement
    on Nov 26, 2026
  2. ptr727 commented on Nov 27, 2026

    @ptr727
    OwnerAuthor

    References for the implementer, 2026-11-26 triage (added at the maintainer's request):

  3. ptr727 commented on Nov 27, 2026

    @ptr727
    OwnerAuthor

    Design Settled, 2026-11-27

    The maintainer decided the open points, and a prototype ran the stop matrix on .NET 11. The rule text follows in a pull request that links here.

    Decisions

    • An interrupted run ends by re-sending the signal after cleanup. It returns 128 plus the signal number only where the signal cannot end it, as PID 1 or on Windows. This reverses the recommendation above, and it matches the script rule.
    • Stop requests escalate. The first asks the tools to stop, with a bounded grace. The second kills the tools at once, and cleanup still runs. The third ends the process.
    • SIGINT, SIGTERM, and SIGHUP are stop requests. SIGQUIT stays unhandled, as the immediate exit.
    • A long-running command stopped by a signal exits like any interrupted run.
    • Child handling uses .NET 11. Each app moves to .NET 11 first, and no .NET 10 workaround is built.

    Corrections to the Text Above

    • PhotoCleaner's row is out of date. It registers its own SIGINT and SIGTERM handlers before any other work, and it ends by re-sending the signal.
    • System.CommandLine registers SIGINT and SIGTERM only, through PosixSignalRegistration. It uses Console.CancelKeyPress and ProcessExit only on targets without that type.
    • Its handler exists only for an asynchronous main action. A synchronous action gets none, under InvokeAsync too.
    • It returns 130 or 143 only when its timeout expires. An action that cancels cooperatively exits 1, through the default exception handler.
    • Timeout.InfiniteTimeSpan is not a usable setting. The handler then blocks the signal thread until the action ends. The app's own registration with ProcessTerminationTimeout = null is the one arrangement that works.
    • An app with no SIGTERM registration is not ended at once as PID 1. The runtime re-sends the signal with its default action, which the kernel drops for PID 1. The container then runs until its stop timeout.
    • CancellationTokenSource.Cancel() runs its callbacks on the calling thread. In a signal handler that is the signal thread, so the handler calls CancelAsync().

    The Rules

    1. One lifetime owner, created first in an asynchronous Main. It registers the stop signals before parsing or logging. It owns a graceful stop token, a forceful kill token, and the recorded stop reason. Its token sources are never disposed.
    2. Stop requests escalate. The first records the signal, cancels the stop token with CancelAsync(), and arms the kill token with CancelAfter. The second cancels the kill token. The third cancels the kill token synchronously and leaves context.Cancel unset. The handler does nothing else but log one line, inside a catch-all.
    3. The kill bound sits below the container stop grace. Docker's default grace is 10 seconds, so a default such as 5 seconds leaves time for cleanup.
    4. A Windows console close blocks in the handler. The process ends when that handler returns. So it cancels both tokens, then waits under 5 seconds for cleanup to finish.
    5. System.CommandLine handles neither signals nor exceptions. ProcessTerminationTimeout is null and EnableDefaultExceptionHandler is false. Actions take (ParseResult, CancellationToken), and InvokeAsync receives the stop token. Main holds one try, and its finally flushes the log.
    6. Cancellation is a parameter end to end. No static accessor reads it, and no call blocks on a task.
    7. A fault is its own stop reason. A callback off the main flow catches its exception and reports a fault. Any stop arms the kill bound. The exit follows the recorded reason, a fault first, then a signal, then the result.
    8. One function runs every child tool. On Unix the child starts in its own session, with StartDetached and all standard streams redirected. Only the app then stops it, once. KillOnParentExit is set where the platform supports it. A stop that was requested means cancelled, and any other signal death is a tool failure. Anything a child starts that outlives it, such as a container, is removed by name in the stop path.
    9. An unhandled exception is logged, not survived. The handler writes it to standard error, kills the tools, and flushes the log under a bound. The runtime then aborts, so the status and any crash dump remain.
    10. Persistent state is written beside its target, flushed to disk, and renamed over it.
    11. An app that runs children owes a signal test. It covers the process group and the app alone. A calling shell loop that does not continue proves death by the signal. The PID 1 path runs in the image.

    Measured on .NET 11

    The prototype is a console app on .NET 11.0.0, System.CommandLine 3.0.0, and CliWrap 3.10.5, in the mcr.microsoft.com/dotnet/sdk:11.0 image. Its child is a shell script that logs each signal it receives.

    Stop Reaches App result Child
    SIGINT to the app App Died by SIGINT after cleanup One SIGINT, own session
    SIGINT to the process group App only, child detached Died by SIGINT One SIGINT
    SIGINT to the process group, child not detached App and child Died by SIGINT Two SIGINT
    Ctrl-C typed at a pty, two children App only Died by SIGINT One SIGINT each
    SIGTERM, SIGHUP to the app App Died by that signal One SIGINT
    Child ignores SIGINT, bound 3 s App Died by SIGINT at 3 s Killed at the bound
    Second SIGINT after 1 s, bound 30 s App Died by SIGINT at once Killed at the second
    Third SIGINT while cleanup hangs App Died by SIGINT with no flush Already killed
    SIGKILL to the app, KillOnParentExit set App Killed None left
    SIGKILL to the app, not set App Killed Left running
    SIGQUIT to the app App Died by SIGQUIT, core None left
    Exception on a pool thread n/a Logged, flushed, died by SIGABRT None left
    Fault from a callback n/a Exit 1 after cleanup One SIGINT
    SIGINT to the child only Child Tool failure, exit 2 Exit 130
    Calling bash loop, SIGINT to the group App Loop stopped One SIGINT
    docker stop, app as PID 1 PID 1 Exit 143 in 1.3 s One SIGINT
    docker kill --signal INT and HUP, PID 1 PID 1 Exit 130 and 129 One SIGINT
    docker stop under --init App Exit 143 One SIGINT
    docker stop, child ignores SIGINT, PID 1 PID 1 Exit 143 in 5.2 s Killed at the bound
    Third SIGINT while cleanup hangs, PID 1 PID 1 Exit 130 Already killed
    Exception on a pool thread, PID 1 n/a Logged, flushed, exit 139 None left
    Ctrl-C typed at docker run -it PID 1 Exit 130 One SIGINT each

    Notes for the Rule Text

    • A child inherits an ignored SIGINT. A non-interactive shell starts a background job with SIGINT ignored. The app's registration then never fires for SIGINT, and its children ignore the graceful stop. A SIGTERM still stops the app, and the kill bound ends the children. A signal test starts the app with default dispositions, as env --default-signal=INT,QUIT does.
    • The third signal ended the process as PID 1 too, with status 130. The runtime path behind that was not traced.
    • The double delivery is real without the session. A child left in the app's process group received two SIGINT, the terminal's and the app's.
    • KillOnParentExit has no macOS support. A child there outlives an app that is killed.
    • Windows is from sources only. No run covers the console close, Ctrl-C, or the job object. StartDetached is left unset there, since the graceful stop attaches to the child's hidden console.
    • The internal CLR error in PlexCleaner's issue stays unexplained. No managed handler sees such a fault, so a crash dump is the only capture.

    A second rule set, for per-item state and parallel work, is filed as its own issue.

  4. ptr727 commented on Nov 27, 2026

    @ptr727
    OwnerAuthor

    Also Measured on musl

    The same prototype ran in the mcr.microsoft.com/dotnet/sdk:11.0-alpine image, since an Alpine image is a shipping base in the fleet.

    • LibraryImport("libc") resolves there, and the re-sent signal ends the app. SIGINT, SIGTERM, and SIGHUP each ended it by that signal after cleanup.
    • The child started in a session of its own and received one SIGINT in each case.
    • A SIGKILL of the app left no child, so KillOnParentExit holds on musl too.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions