Skip to content

PTY support #128565

Open
Open

Description

@adamsitnik

There is currently no built-in way in .NET to:

  • Create a pseudo-terminal (PTY)
  • Spawn a child process with the PTY as its controlling terminal
  • Interact with the process via the PTY master side

We have recently introduced new APIs that will help:

We need to do some research, find the gaps, build a prototype and propose new APIs.

Activity

  1. self-assigned this
    on May 25, 2026
  2. added
    untriaged
    on May 25, 2026
  3. dotnet-policy-service commented on May 25, 2026

    @dotnet-policy-service
    Contributor

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

  4. dotnet-policy-service commented on May 25, 2026

    @dotnet-policy-service
    Contributor

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

  5. dotnet-policy-service commented on May 25, 2026

    @dotnet-policy-service
    Contributor

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

  6. dotnet-policy-service commented on May 25, 2026

    @dotnet-policy-service
    Contributor

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

  7. removed
    untriaged
    on May 25, 2026
  8. MihuBot commented on May 25, 2026

    @MihuBot

    I'm a bot. Here is a possible related and/or duplicate issue (I may be wrong):

  9. adamsitnik commented on May 25, 2026

    @adamsitnik
    MemberAuthor

    I'm a bot. Here is a possible related and/or duplicate issue (I may be wrong):

    Related, but not duplicate (as it's a discussion, not an issue). Anyway this is useful

  10. TeddyAlbina commented on May 25, 2026

    @TeddyAlbina

    Amazing

  11. MattParkerDev commented on May 25, 2026

    @MattParkerDev

    I am building a .NET IDE (SharpIDE) - PTY APIs would be very helpful!

    Prior art: https://github.com/tomlm/Porta.Pty

  12. Tyriar commented on May 26, 2026

    @Tyriar
    Contributor

    You might already know but here's the module used in node: https://github.com/microsoft/node-pty

    You'll need a separate implementation for Windows as it uses an emulation layer called ConPTY. Also on Windows you also have the problem of having ConPTY shipped with the OS, so it takes a long time for changes to land and you'll forever have users on the old version. The solution in node-pty was to eventually bundle the dll that's shipped with Windows Terminal, so you may want to just opt for that approach from the get go.

  13. tmds commented on May 26, 2026

    @tmds
    Member

    I would assume these APIs serve a niche audience of people building terminal emulators? Or are there other use-cases?

  14. 9 remaining items

  15. mitchdenny commented on Jun 3, 2026

    @mitchdenny
    Member

    I don't think there are many tools that refuse to work over pipes.

    I'm not sure what your experience is with automating CLI tools from C#, but even when you spawn a PowerShell process, some functionality is degraded. For example, prompt text that should be displayed with Read-Host is not in output, and there are no console codes for colors when using Write-Host with color parameter.

    I've also come across several popular CLI tools that refuse to be run when they detect the absence of a proper VT-compatible terminal host. One example is the Azure CLI (az).

    This is exactly why I put all the work in the Hex1b that I did. Hex1b is a .NET library but it also bundles a native binary that launches processes like PowerShell with a proper PTY attached to it to handle things like resizing and example. The native binary then tunnels the PTY traffic to Hex1b and handles things like resize events etc. Its extremely composable and absolutely works for PowerShell. Its all about getting the PTY setup correct.

  16. mitchdenny commented on Jun 3, 2026

    @mitchdenny
    Member

    Are you sure az does not run without a terminal? That would mean it doesn't work in a CI pipeline, like GitHub Actions.

    The Azure CLI team is looking to add some TUI like experiences in the future (they are actually looking at Hex1b for this, among other candidates).

    Being able to present a real PTY is incredibly important for end to end testing even if you are building a CLI experience. For example if you want to properly test a CLI that presents interactive prompts via something like Spectre Console and verify the product behavior you need something that can do PTY.

    Here is an example of how we use Hex1b in Aspire to do E2E CLI automation:

    https://github.com/microsoft/aspire/blob/98cfa49941e36cb071f35c53ba11f41caccfa2d8/tests/Aspire.Cli.EndToEnd.Tests/PythonReactTemplateTests.cs#L19

    These tests allow us to use the product the user would.

  17. mitchdenny commented on Jun 3, 2026

    @mitchdenny
    Member

    Given the current interest in AI-driven automation, I think adding support for virtual terminals (VTs) could be particularly valuable. It would enable the creation of an MCP bridge that can expose and orchestrate existing software regardless of whether it was originally designed as a traditional CLI tool or as an interactive terminal application, allowing AI systems to leverage a much broader ecosystem of existing tools.

    In Hex1b I've got two things for general purpose automation by users and LLMs. I have an MCP server (package: Hex1b.McpServer) and I also have the Hex1b dotnet tool (Hex1b.Tool). Both allow you to spawn PTYs and automate them and connect to them remotely.

  18. mitchdenny commented on Jun 3, 2026

    @mitchdenny
    Member

    Here is an example of what we are looking to get going in Aspire via solid PTY and terminal emulation support (all built with .NET and a tiny sprinkling of C which hopefully this issue might eliminate in the future:

    Screen.Recording.2026-06-03.at.3.36.21.pm.mov

    (a few little glitches in there not sure where they are coming from, but the Aspire support is still WIP)

  19. mitchdenny commented on Jun 3, 2026

    @mitchdenny
    Member

    Feedback from the Hex1b project — a cross-platform .NET TUI library that currently ships ~3,500 lines of PTY interop (a native C shim libhex1binterop for Unix, a direct ConPTY implementation for Windows, and an out-of-process AOT helper hex1bpty.exe to make ConPTY behave under nesting + AOT). Our goal in commenting is to identify the raw capabilities that, if exposed by the runtime, would let us delete all of that.

    We've deliberately framed this as capabilities, not API shape — the design is yours.

    Capabilities we'd need to retire our interop layer

    # Capability What we do today Why we need it from the runtime
    1 Allocate a pseudo-terminal pair on Unix (posix_openpt/grantpt/unlockpt or BSD openpty) Done implicitly by forkpty() in our C shim Foundation; nothing else works without it
    2 Allocate a Windows pseudoconsole (ConPTY) CreatePseudoConsole in our Windows handle First-class Windows support is non-negotiable; this issue currently scopes only setsid/Unix
    3 Specify initial PTY size (cols × rows) at creation, not after spawn winsize passed to forkpty, COORD passed to CreatePseudoConsole Setting size after start causes visible reflow in vim/tmux/less
    4 Spawn a child process whose stdin/stdout/stderr are the PTY slave forkpty dups the slave; ConPTY attribute does the equivalent Core of "interactive child"
    5 Guarantee the child becomes session leader AND acquires the PTY as its controlling terminal forkpty does setsid + TIOCSCTTY; StartDetached in .NET 11 only covers setsid Without TIOCSCTTY job control breaks, tmux/screen refuse to start, Ctrl-C/Ctrl-Z don't reach the foreground group
    6 Independent control over the child's termios — at minimum the ability to give the child default cooked-mode termios even when the parent process is already in raw mode We pass NULL for the termios arg to forkpty deliberately Hex1b enters raw mode before spawning the child; if termios is inherited the child has echo off and nested shells/tmux are broken
    7 Reset child's signal disposition to SIG_DFL for all catchable signals before exec Manual loop over 1..NSIG in our child branch Otherwise the child inherits ignored/handled signals from the host
    8 Set child's working directory, environment, and argv — including the ability to set argv[0] independently of the executable path (e.g. -bash for login shells) Done in our C shim and managed code Process.Start doesn't give us argv[0] control; login shells need this
    9 Asynchronous byte-stream read from the PTY master with correct EOF semantics when the child exits Hand-rolled select(100ms) + kill(pid, 0) loop on Unix; background thread + Channel<byte[]> on Windows macOS in particular has racy EOF on PTY masters; we need a clear contract that "child exited → reader observes end of stream"
    10 Asynchronous byte-stream write to the PTY master, partial-write safe, raw bytes (not line-oriented) write loop with EINTR handling on Unix; background thread + channel on Windows TUI traffic is binary ANSI; line-mode would corrupt it
    11 Resize a live PTY (TIOCSWINSZ / ResizePseudoConsole) and have SIGWINCH delivered to the child hex1b_resize and ResizePseudoConsole Required for any responsive TUI
    12 Send arbitrary POSIX signals to the child or its process group (not just terminate) kill(pid, sig) P/Invoke Process.Kill is too coarse; we need SIGTERM/SIGHUP/SIGINT/SIGWINCH/SIGUSR1 etc., targetable at the group
    13 Retrieve exit status that distinguishes normal exit from signal termination (and which signal) WIFEXITED/WIFSIGNALED/WTERMSIG in our wait, encoded as 128+sig Currently this fidelity is lost behind Process.ExitCode
    14 A defined teardown ordering contract: close master → hang up → wait → reap, with no zombies and no hangs if the child is wedged Custom dispose logic in both Unix and Windows handles; we maintain dedicated dispose tests Today this is our number-one source of platform-specific bugs
    15 Work correctly when the host process is itself running inside a PTY slave (nested PTYs) Hex1b hosts Hex1b in samples and tests; we carry a HEX1B_NESTING_LEVEL workaround Many TUI use cases (tmux-in-tmux, dev loops, CI recorders, embedded terminal panes) require this — see the stress test below
    16 AOT-publishable with no hidden thread-pool / finalizer / static-initializer assumptions that misbehave during process shutdown on Windows The in-process WindowsPtyHandle is so fragile under AOT + nesting + shutdown that we run it out-of-process via hex1bpty.exe by default This single capability would let us delete an entire helper project, a framed binary/JSON protocol, a Unix-domain socket transport, and per-RID packaging machinery
    17 Detect whether a given handle/fd is a PTY (isatty) and query its current size Not currently in our shim but would replace ad-hoc probes elsewhere Useful for adapters that need to behave differently when wrapped vs. attached to a real terminal
    18 Cross-platform packaging: the capability ships in the BCL, not as per-RID native assets we redistribute We ship libhex1binterop.{so,dylib} for linux-x64/arm64 + macOS-x64/arm64, plus hex1bpty.exe for win-x64/arm64 Removing these is the visible win for downstream consumers of our NuGet

    Where the implementation effort really hides

    • Rows 1–4 are what the issue already implies.
    • Rows 5, 6, 14 are the ones most likely to be quietly skipped by a "minimum viable PTY" prototype, and they are the ones that matter most for real TUI workloads. We'd push hardest on these.
    • Row 16 (AOT) is worth raising as a first-class requirement, not an afterthought — it is literally the reason we have a second process on Windows.
    • Rows 12 + 13 together are the "POSIX faithfulness" point: System.Diagnostics.Process is currently too lossy for terminal-multiplexer scenarios.

    The step-function from "TUI with a PTY child" → "terminal emulator that nests"

    A TUI that spawns a single PTY child (chat client launching vim) needs rows 1–14 working once, at one layer:

    real terminal ─┬─► host TUI (raw mode, owns stdin/stdout)
                   └─► PTY ─► child (cooked mode, thinks it's on a terminal)
    

    A terminal-emulator TUI does the same thing, but its own stdin/stdout may themselves be a PTY slave being driven by some outer terminal-emulator TUI. Every capability now has to compose cleanly across N layers:

    real terminal ─► Hex1b instance 1 (raw mode) ─► PTY₁ ─► Hex1b instance 2 (raw mode) ─► PTY₂ ─► Hex1b instance 3 ─► PTY₃ ─► bash
    

    At each layer, independently:

    • termios / console-mode state must be tracked and restored on teardown without leaking up or down,
    • the host must be in raw mode on its inbound side while the child gets cooked-mode defaults on its slave (capability 6),
    • SIGWINCH must propagate down the stack as the user resizes the outermost window,
    • signal handlers, env vars, fds/handles, and ConPTY/forkpty resources owned at one layer must not be visible to the layers below,
    • teardown ordering (capability 14) must work in both directions.

    It is entirely possible to have rows 1–14 working perfectly for the single-layer case and have nesting break at layer 2.

    What we had to do on Windows specifically

    The in-process direct-ConPTY path works for the single-layer case but is unstable under nesting and under AOT. The failure modes we hit:

    • ConPTY I/O is implemented as anonymous pipes driven by background threads inside our process. When the host process is itself running inside a ConPTY, you now have two ConPTY sessions sharing one process's thread pool, handle table, and shutdown path. Reads and writes interleave in ways that wedge during dispose.
    • Windows console-mode bits (ENABLE_VIRTUAL_TERMINAL_INPUT, ENABLE_PROCESSED_INPUT, DISABLE_NEWLINE_AUTO_RETURN, etc.) are process-global. Nested instances clobber each other's state if any layer is sloppy about save/restore — and the runtime's own Console class touches these too.
    • AOT publishing amplifies the above because finalizer / static-initializer ordering during shutdown differs from JIT.

    Our fix was to take ConPTY hosting out of process. The default mode is RequireProxy: every PTY launch spawns a small managed AOT helper (hex1bpty.exe), connects to it over a Unix-domain socket, and exchanges a framed binary/JSON protocol (launch / output / input / resize / kill / exit / shutdown). The helper is the only thing that ever calls CreatePseudoConsole, owns the pipes, and runs the background read/write threads. When the helper exits, everything ConPTY-related dies with it — no state leaks back into the host. This is what makes nesting work reliably on Windows today, and it's the single biggest piece of plumbing that fixing rows 6, 14, and 16 in the runtime would let us delete.

    On Unix we don't need an out-of-process helper because forkpty() gives strong layering for free (each layer's PTY is just another fd; setsid + TIOCSCTTY cleanly isolate controlling-terminal state per session). But we do still depend on capability 6 at every layer.

    The nesting stress test we'd ask you to actually run

    Build release samples/WindowingDemo from the Hex1b repo, then:

    1. Run it in a real terminal (Windows Terminal / iTerm2 / GNOME Terminal).
    2. Inside the demo, open a terminal pane and run the same WindowingDemo binary inside it.
    3. Inside that nested instance, open another terminal pane and run WindowingDemo again.
    4. Repeat to at least 3–4 levels of nesting.
    5. At the deepest level, run vim, then tmux, then resize the outermost window.

    Pass criteria: every layer renders correctly, keystrokes reach the innermost process, the resize propagates all the way down (vim redraws at the new size), Ctrl-C reaches only the foreground process at the bottom, and tearing down from the inside out leaves the outer terminal in a clean state with no orphaned processes, no stuck raw mode, and no leaked PTY fds/handles.

    This composes termios/console-mode save-restore correctness at every layer, forkpty/ConPTY teardown ordering at every layer, SIGWINCH propagation across N hops, exit-status fidelity across N hops, and AOT stability across N hops on Windows.

    This combination is uncommon to get right on either Windows or Linux. Most "PTY support" libraries in either ecosystem are validated only against the single-layer case (a host spawning bash, python, or vim). Terminal multiplexers and IDE terminal panes that pass this test (tmux, screen, Windows Terminal hosting WSL hosting tmux) get there through years of platform-specific workarounds, not because the underlying APIs make it easy. If the new runtime PTY support passes the nested WindowingDemo test on day one, it has crossed the bar that matters for Hex1b — and almost any other .NET TUI library that wants to be more than a single-shot wrapper.

  20. tmds commented on Jun 3, 2026

    @tmds
    Member

    Great overview @mitchdenny!

    Rows 5, 6, 14 are the ones most likely to be quietly skipped by a "minimum viable PTY" prototype, and they are the ones that matter most for real TUI workloads. We'd push hardest on these.

    +1. None of these are particularly complex, but all are important to get it right.

    Rows 12 + 13 together are the "POSIX faithfulness" point: System.Diagnostics.Process is currently too lossy for terminal-multiplexer scenarios.

    There are new Process API in .NET 11. @adamsitnik's recent blog post describes them: https://devblogs.microsoft.com/dotnet/process-api-improvements-in-dotnet-11/.

    1. Set child's working directory, environment, and argv — including the ability to set argv[0] independently of the executable path (e.g. -bash for login shells)

    There is an open issue for this: #101837.

    Actually, this issue is for reading the raw argv[0], not for setting it.

    Here you want to set the argv[0] to prefix with a dash so that the started shell behaves like a login shell.

  21. mitchdenny commented on Jun 3, 2026

    @mitchdenny
    Member

    @tmds yep @adamsitnik shared the Process API improvements a while ago. I'm excited about them for general purpose scenarios and if we can get PTY support in there layered on top I can delete a bunch of code (hopefully).

  22. adamsitnik commented on Jun 3, 2026

    @adamsitnik
    MemberAuthor

    @mitchdenny big thanks for sharing a very detailed requirements

    • Point 1-5 (create PTY, spawn a process, configure PTY) included in the proposed design.
    • Point 6 (Independent control over the child's termios) the proposed design would allow for exposing this at later stage (via new property in the option bag)
    • Point 7 (Reset child's signal disposition to SIG_DFL for all catchable signals before exec) is easy to implement, but also very niche (?). I saw PowerShell also customizing signals, but in a different way.
    • Point 8 (Process.Start doesn't give us argv[0] control): Do you mean doing things like changing arg[0] to -bash for Process.Start("/bin/bash", "--myArg 123")? This also seems very niche.
    • Point 9 & 10 (Asynchronous byte-stream): On Windows, it should just work with the most recent changes. On Unix, I need to check whether we can hack Socket to work with PTY the same way we hacked it for pipes.
    • Point 11 (Resize a live PTY) included in the proposed design.
    • Point 12 (Send arbitrary POSIX signals to the child or its process group (not just terminate)): possible with the recently introduced SafeProcessHandle.Signal (and I am looking for data to justify SignalGroup)
    • Point 13 (Retrieve exit status that distinguishes normal exit from signal termination): possible with the recently introduced ProcessExitStatus
    • Point 14 (A defined teardown ordering contract) I need more data, but seems doable.
    • Point 15 (Work correctly when the host process is itself running inside a PTY slave): @mitchdenny what are the tricky parts here? Assuming that I create new PTY, fork the process, configure the PTY and run exec?
    • Point 16 (AOT-publishable with no hidden thread-pool / finalizer / static-initializer assumptions): I need more data.
    • Point 17 (Detect whether a given handle/fd is a PTY (isatty) and query its current size): doable, could be exposed via the PseudoTerminal class
    • Point 18 (Cross-platform packaging: the capability ships in the BCL, not as per-RID native assets we redistribute): Working OOTB, but only for .NET 11+.

    signal handlers, env vars, fds/handles, and ConPTY/forkpty resources owned at one layer must not be visible to the layers below,

    For signals, I think we do it by default:

    // Remove all signals, then restore signal mask.

    For env vars, they are always inherited by default by design, but the users can modify the env vars and explicitly remove some of the variables.

    For fds/handles we do provide a dedicated API for that now: https://devblogs.microsoft.com/dotnet/process-api-improvements-in-dotnet-11/#handle-inheritance

    The only problem I see is that to achieve that we need to use posix_spawn on macOS. So if we want to use fork/forkpty on macOS, we will have to go over all opened fds and apply the FD_CLOEXEC flag (perf hit).

    When it comes to ConPTY/forkpty resources, we can't prohibit that. To make given child inherit the handle, we need to make it inheritable. From there child is responsible for not passing it further (by for example using the InheritedHandles API or redirecting to specific handles different than parent standard handles)

    What we had to do on Windows specifically

    @mitchdenny what exactly was the main source of the problems on Windows? Inheriting all handles by default? Performing sync IO on thread pool? Maintaining the lifetime of the pseudo handle created with CreatePseudoConsole?

    The nesting stress test we'd ask you to actually run

    Big thanks for providing the stress test!

  23. mitchdenny commented on Jun 3, 2026

    @mitchdenny
    Member

    Adding @danegsta for his thoughts on signal groups. I think he was having some fun with that one on the DCP side of Aspire and might have some perspectives to share (even though DCP is built in Go).

  24. tmds commented on Jun 4, 2026

    @tmds
    Member

    Point 8 (Process.Start doesn't give us argv[0] control): Do you mean doing things like changing arg[0] to -bash for Process.Start("/bin/bash", "--myArg 123")? This also seems very niche.

    Yes, the shell executables behave like a login shell (read /etc/profile, ...) when they see the first char of arg[0] is a dash.

    Normally the shell executable also has an argument for this. Typically, -l.

  25. tmds commented on Jun 16, 2026

    @tmds
    Member

    @adamsitnik the SSH library I maintain supports executing processes with a pty, applying its API to Process would translate to something like:

    public partial class ProcessStartInfo
    {
        public bool AllocateTerminal { get; set; }
        public int TerminalWidth { get; set; } = 80;
        public int TerminalHeight { get; set; } = 24;
        public string? TerminalType { get; set; } = "xterm-256color";
    }
    public partial class Process
    {
        public bool HasTerminal { get; }
        public void ResizeTerminal(int width, int height);
    }

    (There's also a TerminalSettings property for ProcessStartInfo which are a bunch of things I doubt anyone is every changing, so I've not included it.)

    This API makes the Process instance responsible for disposing the terminal when it is no longer needed, instead of giving that in the user's hands.

  26. adamsitnik commented on Jun 18, 2026

    @adamsitnik
    MemberAuthor

    This API makes the Process instance responsible for disposing the terminal when it is no longer needed, instead of giving that in the user's hands.

    The reason why my current proposal makes user responsible for PTY lifetime is that without it I can't provide an API that will allow to start multiple processes using same PTY. This is advanced feature, but some of the OSS libs support it.

  27. added this to the 12.0.0 milestone on Jul 14, 2026
  28. kasperk81 commented on Aug 5, 2026

    @kasperk81
    Contributor
    • and I am looking for data to justify SignalGroup

    another place that requires group wide signaling to suspend the pipe siblings and children https://github.com/tui-cs/Terminal.Gui/blob/13a0981ad04bdaa2145c5e19c3faed0038c78c59/Terminal.Gui/Drivers/UnixHelpers/SuspendHelper.cs#L27

  29. ghostflyby commented on Aug 26, 2026

    @ghostflyby

    It seems not possible to use only posix_spawn on macOS, as the POSIX_SPAWN_SETSID will be after file_actions at least in some cases I encountered, making it not possible to specify the controlling terminal by opening the pty.

    But according to man posix_spawnattr_setflags, posix_spawn can be used as a featureful execve.

    POSIX_SPAWN_SETEXEC          Apple Extension: If this bit is set, rather
                                 than returning to the caller, posix_spawn(2)
                                 and posix_spawnp(2) will behave as a more
                                 featureful execve(2).
    

    So fork/forkpty could be used in combine with posix_spawn

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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions