pty

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 23, 2026 License: MIT Imports: 11 Imported by: 0

README

pty

A Go package for pseudo-terminals, on every platform:

  • Real pseudo-terminals on Unix, from the /dev/ptmx cloning device, with helpers to start a command on one and to query and resize terminals.
  • Real pseudo-consoles on Windows, through ConPTY, the console host Windows offers instead of pseudo-terminal devices.
  • Virtual pseudo-terminals everywhere: an in-memory terminal pair with a line discipline that needs neither operating system support nor a child process, so that a program expecting to talk to a terminal can run inside the process that drives it.
  • Commands on a terminal, in the spirit of os/exec, for the terminals that host a process: a Windows pseudo-console and a virtual terminal.
  • SSH terminal modes: the settings an SSH client sends in its pseudo-terminal request, applied to a terminal.

Install

go get github.com/malivvan/pty

Platform support

System Real pty ConPTY Virtual pty SSH modes
Linux, Android yes no yes yes
macOS, iOS yes no yes yes
FreeBSD, NetBSD, OpenBSD, DragonFly BSD yes no yes yes
Solaris, illumos yes no yes yes
z/OS yes no yes no
Windows no yes yes no
AIX, Plan 9, js/wasm, wasip1/wasm no no yes no

Everything the package cannot do on a given system fails with pty.ErrUnsupported, so portable programs keep compiling and can degrade gracefully.

Running a command on a real pseudo-terminal

pty.Start allocates a pair, connects the standard streams of the command to the slave end, starts it in a new session with that slave as its controlling terminal, and hands back the master end:

package main

import (
	"io"
	"log"
	"os/exec"

	"github.com/malivvan/pty"
)

func main() {
	cmd := exec.Command("grep", "--color=always", "bar")

	ptmx, err := pty.Start(cmd)
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = ptmx.Close() }() // Best effort.

	go func() {
		_, _ = ptmx.Write([]byte("foo\n"))
		_, _ = ptmx.Write([]byte("bar\n"))
		_, _ = ptmx.Write([]byte("baz\n"))
		_, _ = ptmx.Write([]byte{4}) // EOT
	}()

	_, _ = io.Copy(os.Stdout, ptmx)
}

pty.StartWithSize resizes the terminal before the command starts, and pty.StartWithAttr exists for the cases that need the process attributes to be set up differently. A command created with exec.CommandContext is stopped when its context is done, exactly as it would be without a pseudo-terminal.

Driving an interactive program

To drive a program as if it were running in the terminal of the user, put that terminal in raw mode with golang.org/x/term and forward its size to the pty whenever it changes:

ptmx, err := pty.Start(exec.Command("bash"))
if err != nil {
	return err
}
defer func() { _ = ptmx.Close() }() // Best effort.

winch := make(chan os.Signal, 1)
signal.Notify(winch, syscall.SIGWINCH)
defer func() { signal.Stop(winch); close(winch) }() // Best effort.

go func() {
	for range winch {
		if err := pty.InheritSize(os.Stdin, ptmx); err != nil {
			log.Printf("resizing pty: %v", err)
		}
	}
}()
winch <- syscall.SIGWINCH // Initial resize.

go func() { _, _ = io.Copy(ptmx, os.Stdin) }()
_, _ = io.Copy(os.Stdout, ptmx)

pty.InheritSize reads the size of one terminal and applies it to another; pty.GetSize and pty.GetFullSize report it, and pty.SetSize changes it.

Real pseudo-consoles on Windows

Windows has no pseudo-terminal devices, so the package offers ConPTY: a console host that a process is attached to and that is driven over a pair of pipes.

console, err := pty.NewConPTY(pty.DefaultWidth, pty.DefaultHeight, 0)
if err != nil {
	return err
}
defer func() { _ = console.Close() }() // Best effort.

pid, handle, err := console.Spawn("cmd.exe", []string{"cmd.exe", "/c", "echo hello"}, nil)
if err != nil {
	return err
}
// The process handle belongs to the caller.
defer windows.CloseHandle(windows.Handle(handle))

log.Printf("started process %d", pid)

// A ConPTY is an io.Reader for the output of the command and an io.Writer for
// its input.
_, err = io.Copy(os.Stdout, console)
return err

pty.NewConPTYWithPipes accepts pipes the caller created with pty.CreatePipes, or in any other way, which is useful when the process is started somewhere else. ConPTY.Resize and ConPTY.Size change and report the size of the pseudo-console.

Running a command on a terminal

A terminal that can host a process hands out commands, in the spirit of os/exec. This is what makes running a command on a pseudo-terminal portable: on Windows a process cannot be attached to a console with os/exec, and a virtual terminal has no device to attach it to at all.

// A command inside a Windows pseudo-console.
console, err := pty.NewConPTY(pty.DefaultWidth, pty.DefaultHeight, 0)
if err != nil {
	return err
}
defer func() { _ = console.Close() }() // Best effort.

cmd := console.Command("cmd.exe", "/c", "echo hello")
if err := cmd.Run(); err != nil { // Start and Wait.
	return err
}
log.Printf("the command exited with %v", cmd.ProcessState)

The fields of Cmd are the ones of os/exec.Cmd that every terminal can honour: Path, Args, Env, Dir and SysProcAttr, plus Process and ProcessState once the command has run. CommandContext adds a context: the process is killed when the context is done, unless Cmd.Cancel says otherwise, and Wait reports the cancellation.

Virtual pseudo-terminals

A virtual terminal is an in-memory pair with a line discipline: input is echoed, only complete lines reach the program behind it, the erase and end-of-file characters are processed, and the line feeds the program writes are expanded to carriage return plus line feed. VirtualPTY.SetRaw turns all of that off.

Like a real terminal it holds a bounded amount of input and output, and the writer waits when the other side has not read what it holds, so neither side of it can grow memory without bound.

Because it is not a device, a virtual terminal hosts commands in the process itself, through their standard streams:

vt := pty.NewVirtualPTY(80, 24)
defer vt.Close()

cmd := vt.Command("bash")
if err := cmd.Start(); err != nil {
	return err
}

// Type a command on the terminal and read what the shell answers.
if _, err := vt.Write([]byte("echo hello\n")); err != nil {
	return err
}
_, err = io.Copy(os.Stdout, vt)
return err
Driving a program that runs in the same process

VirtualPTY.Slave returns the end of the terminal the hosted program uses. Handing it to a program that only needs a reader for its input and writers for its output is enough to give that program a terminal, without starting another process. A shell interpreter, such as the one in mvdan.cc/sh/v3, is the classic example:

vt := pty.NewVirtualPTY(80, 24)
defer vt.Close()

runner, err := interp.New(interp.StdIO(vt.Slave(), vt.Slave(), vt.Slave()))
if err != nil {
	return err
}
go func() { _, _ = runner.Run(ctx, script) }()

// Type a command on the terminal and read what the shell answers.
if _, err := vt.Write([]byte("echo hello\n")); err != nil {
	return err
}
_, err = io.Copy(os.Stdout, vt)
return err

A real terminal delivers signals to the programs running on it; a virtual one has no processes to signal, so the interrupt character is reported to the program driving it instead:

ctx, cancel := context.WithCancel(context.Background())
vt.OnInterrupt(cancel) // ^C cancels whatever the hosted program is doing.

SSH pseudo-terminals

An SSH server receives the settings of the terminal of its client in the pty-req request of a session, and has to apply them to the pseudo-terminal the session runs on. ApplyTerminalModes does that, and resizes the terminal at the same time:

var req struct {
	Term   string
	Cols   uint32
	Rows   uint32
	Width  uint32
	Height uint32
	Modes  ssh.TerminalModes
}
if err := ssh.Unmarshal(payload, &req); err != nil {
	return err
}

ptmx, err := pty.Start(exec.Command("/bin/sh"))
if err != nil {
	return err
}
defer func() { _ = ptmx.Close() }() // Best effort.

// ssh.TerminalModes is a map[uint8]uint32, which is exactly what
// ApplyTerminalModes takes, so the modes of the request are passed as they are.
if err := pty.ApplyTerminalModes(int(ptmx.Fd()), int(req.Cols), int(req.Rows), req.Modes); err != nil {
	return err
}

The keys of the modes are the opcodes of RFC 4254 section 8, which this package also exports as the Mode* constants, so an SSH server that does not use an SSH library can build them itself. A mode the system does not have is ignored: a client asks for its terminal settings, it does not demand them.

The modes are applied on the systems where the package can drive terminal settings, which are the ones where it can allocate a pseudo-terminal as well: Linux, macOS, the BSDs and Solaris/illumos. Elsewhere the function reports ErrUnsupported.

The terminal interface

ConPTY and VirtualPTY are both terminals driven through a single value, and both implement pty.Terminal:

type Terminal interface {
	io.ReadWriteCloser
	Resize(width, height int) error
	Size() (width, height int, err error)
	Command(name string, args ...string) *Cmd
	CommandContext(ctx context.Context, name string, args ...string) *Cmd
}

A terminal obtained from Open, Start or StartWithSize is the classic pair of *os.File values instead, driven with Read, Write, GetSize and SetSize.

Non-blocking I/O

The files returned by this package are ordinary *os.File values owned by the caller. Making Close interrupt a concurrent Read, or making deadlines work, requires non-blocking I/O first:

if err := syscall.SetNonblock(int(ptmx.Fd()), true); err != nil {
	return err
}

Reading a pseudo-terminal whose other end is gone reports end of file on some systems and an input/output error on others, so portable code should treat both as the end of the terminal.

Development

The sources use line feeds only, which .gitattributes enforces: an editor that writes carriage returns into them makes make fmt-check, and the workflow, fail on every file.

make            # build, vet and test on the host system
make test-race  # run the tests with the race detector
make test-wasm  # run the tests on js/wasm and wasip1/wasm
make cross      # compile for every supported GOOS/GOARCH pair
make cross-vet  # type-check the package and its tests for all of them
make check      # everything the CI workflow runs on the host system
make help       # list all targets

The tests are laid out by what they cover: open_test.go, winsize_test.go, io_test.go and start_test.go cover the real terminals of the host system, conpty_windows_test.go covers the pseudo-console on Windows, which the CI runs there, ssh_test.go covers the SSH terminal modes, conpty_unsupported_test.go and unsupported_test.go cover the systems without support, and virtual_test.go, virtual_program_test.go and virtual_process_test.go cover the virtual terminal and the commands it hosts, which are tested on every system.

The ztypes_*.go files, which describe the C types and constants of the BSD pseudo-terminal interfaces, are generated by make generate from the types_*.go files next to them. They are the only generated files in the repository, and they are generated on the system they describe, since the generator reads the C headers of the machine it runs on:

GOOS=freebsd GOARCH=arm64 make generate

License

MIT, see LICENSE.

Documentation

Overview

Package pty provides pseudo-terminal support for Unix-like systems and for Windows console pseudo-terminals (ConPTY).

Unix pseudo-terminals

On Unix-like systems a pseudo-terminal is a pair of devices: a master (commonly called the ptmx) and a slave (the pty, or tty). The master end is driven by the program that owns the terminal, the slave end is used by the program that believes it is talking to a real terminal.

This package covers the whole life cycle of such a pair:

Windows pseudo-terminals

Windows has no pseudo-terminal device, but its console host provides ConPTY: a pseudo-console that a child process can be attached to and that is driven through a pair of pipes. Use NewConPTY (or NewConPTYWithPipes to supply the pipes yourself) to create one, ConPTY.Spawn to start a process inside it and ConPTY.Read/ConPTY.Write to exchange data with that process.

Platform support

Unix pseudo-terminals are implemented on Darwin, DragonFly BSD, FreeBSD, Linux, NetBSD, OpenBSD, Solaris/illumos and z/OS. ConPTY is implemented on Windows 10 1809 and later.

On every other system (AIX, Plan 9 and the WebAssembly targets among them) the package still compiles and the same API stays available, but terminal operations fail with ErrUnsupported.

Blocking operations

The files returned by this package are ordinary *os.File values owned by the caller. Making Close interrupt a concurrent Read, or making deadlines work, requires non-blocking I/O: call syscall.SetNonblock on the file descriptor first. See the examples in the repository README.

Index

Examples

Constants

View Source
const (
	DefaultWidth  = 80
	DefaultHeight = 25
)

Default size requested by NewConPTY and NewConPTYWithPipes when they are asked for a non-positive width or height.

View Source
const (
	ModeVINTR    = 1
	ModeVQUIT    = 2
	ModeVERASE   = 3
	ModeVKILL    = 4
	ModeVEOF     = 5
	ModeVEOL     = 6
	ModeVEOL2    = 7
	ModeVSTART   = 8
	ModeVSTOP    = 9
	ModeVSUSP    = 10
	ModeVDSUSP   = 11
	ModeVREPRINT = 12
	ModeVWERASE  = 13
	ModeVLNEXT   = 14
	ModeVFLUSH   = 15
	ModeVSWTCH   = 16
	ModeVSTATUS  = 17
	ModeVDISCARD = 18
	ModeVMIN     = 19
	ModeVTIME    = 20

	ModeIGNPAR  = 30
	ModePARMRK  = 31
	ModeINPCK   = 32
	ModeISTRIP  = 33
	ModeINLCR   = 34
	ModeIGNCR   = 35
	ModeICRNL   = 36
	ModeIUCLC   = 37
	ModeIXON    = 38
	ModeIXANY   = 39
	ModeIXOFF   = 40
	ModeIMAXBEL = 41
	ModeIUTF8   = 42

	ModeISIG    = 50
	ModeICANON  = 51
	ModeXCASE   = 52
	ModeECHO    = 53
	ModeECHOE   = 54
	ModeECHOK   = 55
	ModeECHONL  = 56
	ModeNOFLSH  = 57
	ModeTOSTOP  = 58
	ModeIEXTEN  = 59
	ModeECHOCTL = 60
	ModeECHOKE  = 61
	ModePENDIN  = 62

	ModeOPOST  = 70
	ModeOLCUC  = 71
	ModeONLCR  = 72
	ModeOCRNL  = 73
	ModeONOCR  = 74
	ModeONLRET = 75

	ModeCS7    = 90
	ModeCS8    = 91
	ModePARENB = 92
	ModePARODD = 93

	ModeTTYOpISpeed = 128
	ModeTTYOpOSpeed = 129
)

Terminal mode opcodes of RFC 4254 section 8, the modes an SSH client sends in its pseudo-terminal request. They are the keys of the modes an SSH client asks for, and the values are the settings themselves: the value of a control character opcode is the character, the value of a flag opcode is 1 to set the flag and 0 to clear it, and the value of a speed opcode is a baud rate.

A client that uses golang.org/x/crypto/ssh passes ssh.TerminalModes, which is the same map, to ApplyTerminalModes.

Variables

View Source
var (
	// ErrInvalidCommand is returned by [Cmd.Start] when the command does not
	// come from a terminal that can start processes.
	ErrInvalidCommand = errors.New("pty: invalid command")

	// ErrNilContext is returned by [Cmd.Start] when the command was created
	// with [Terminal.CommandContext] and a nil context, rather than starting a
	// process that nothing can stop.
	ErrNilContext = errors.New("pty: nil context")
)
View Source
var ErrUnsupported = errors.New("pty: unsupported")

ErrUnsupported is returned by functions that have no implementation on the current platform. Use errors.Is to test for it.

Functions

func ApplyTerminalModes

func ApplyTerminalModes(fd int, width, height int, modes map[uint8]uint32) error

ApplyTerminalModes applies the terminal modes of an SSH pseudo-terminal request to the terminal with the given file descriptor, and resizes it to width by height character cells unless both are zero.

modes holds the opcodes of RFC 4254 section 8, the [Mode] constants of this package; ssh.TerminalModes is the same map and can be passed as it is. A mode the system does not have is ignored: a client asks for its terminal settings, it does not demand them.

The file descriptor comes from a terminal of this package, either the master end returned by Open and Start or the end returned by VirtualPTY.Slave, and it must be a terminal.

Systems without terminal settings support report ErrUnsupported.

func CreatePipes

func CreatePipes() (inPipeRead, inPipeWrite, outPipeRead, outPipeWrite uintptr, err error)

CreatePipes creates the two connected pipes a ConPTY is driven through.

Data written to the write end of the input pipe shows up on the standard input of the processes hosted by the pseudo-console; data those processes write to their standard output shows up on the read end of the output pipe. The handles can be inherited by child processes, which is why they can be passed to NewConPTYWithPipes as-is.

func GetSize

func GetSize(tty *os.File) (rows, cols int, err error)

GetSize returns the number of rows and the number of columns of the terminal backed by tty.

func InheritSize

func InheritSize(from, to *os.File) error

InheritSize reads the terminal size of from and applies it to to.

It is commonly used in a SIGWINCH handler to keep a pseudo-terminal in step with the terminal the user is actually looking at:

winch := make(chan os.Signal, 1)
signal.Notify(winch, syscall.SIGWINCH)
for range winch {
	if err := InheritSize(os.Stdin, ptmx); err != nil {
		log.Printf("resizing pty: %v", err)
	}
}

func Open

func Open() (ptmx, tty *os.File, err error)

Open allocates a pseudo-terminal pair and returns its master end (the ptmx) and its slave end (the tty).

Both files belong to the caller, which must close them. Systems without pseudo-terminal support return ErrUnsupported.

func SetSize

func SetSize(*os.File, *Winsize) error

SetSize always fails with ErrUnsupported: the systems this file is built for have no terminal size request. It exists so that portable code keeps compiling.

func Start

func Start(cmd *exec.Cmd) (*os.File, error)

Start starts cmd with its standard input, output and error connected to a freshly allocated pseudo-terminal, and returns the master end of that terminal.

It is equivalent to StartWithSize(cmd, nil): the command is started in a new session with the slave end of the pseudo-terminal as its controlling terminal, so it behaves like a program started from an interactive shell.

The returned file belongs to the caller, which must close it. Systems without pseudo-terminal support return ErrUnsupported.

func StartWithAttr

func StartWithAttr(cmd *exec.Cmd, size *Winsize, attrs *syscall.SysProcAttr) (*os.File, error)

StartWithAttr starts cmd on a freshly allocated pseudo-terminal, resizing the terminal to size first when size is not nil, and returns the master end of that terminal.

attrs is assigned to cmd.SysProcAttr and replaces whatever the caller had put there, which is how the platform specific StartWithSize arranges for cmd to become the session leader that owns the slave end.

Most callers want Start or StartWithSize instead; this variant exists for the rare cases that need a different process setup, such as a command that must not receive a controlling terminal.

func StartWithSize

func StartWithSize(*exec.Cmd, *Winsize) (*os.File, error)

StartWithSize always fails with ErrUnsupported: the systems this file is built for have no pseudo-terminal to start a command on. On Windows, use NewConPTY and ConPTY.Spawn instead.

Types

type Cmd

type Cmd struct {

	// Path is the path of the program to run.
	Path string

	// Args holds the command line arguments, [Cmd.Path] being Args[0].
	Args []string

	// Env is the environment of the process. A nil Env means the environment
	// of the current process.
	Env []string

	// Dir is the working directory of the process. An empty Dir means the
	// current directory.
	Dir string

	// SysProcAttr holds the operating system specific settings of the process.
	SysProcAttr *syscall.SysProcAttr

	// Process is the process, once it has been started.
	Process *os.Process

	// ProcessState describes the process once it has exited.
	ProcessState *os.ProcessState

	// Cancel stops the process when the context of the command is done. It
	// defaults to killing the process with [os.Process.Kill], and has to be
	// set before the command is started.
	Cancel func() error
	// contains filtered or unexported fields
}

Cmd is a command that runs on a pseudo-terminal.

Its fields are the ones of os/exec.Cmd that every terminal can honour. A command always comes from the terminal it runs on, which is what decides how a process is attached to it:

shell := vt.Command("bash")         // a terminal in this process
shell := console.Command("cmd.exe") // the Windows console host

The command is started with Cmd.Start, waited for with Cmd.Wait, and Cmd.Run does both. A command is started and waited for once: the fields below, Cmd.Cancel included, have to be set before Cmd.Start is called, and only one goroutine may do it.

func (*Cmd) Run

func (c *Cmd) Run() error

Run starts the command and waits for it to exit.

func (*Cmd) Start

func (c *Cmd) Start() error

Start starts the command on the terminal it came from.

A command that was created with Terminal.CommandContext is stopped with Cmd.Cancel when its context is done, in the same way os/exec stops a command created with os/exec.CommandContext.

func (*Cmd) Wait

func (c *Cmd) Wait() error

Wait waits for the command to exit and releases what the terminal held for it. It returns an error when the command has not been started, or has already been waited for.

A command whose context is done while it is being waited for is stopped, and reports the error of the context, so that errors.Is(err, context.Canceled) holds on every system, whether the process ends with a signal or with an exit code. A command that had already finished when it was stopped is not blamed on the context, and a command that could not be stopped reports that failure.

type ConPTY

type ConPTY struct {
	// contains filtered or unexported fields
}

ConPTY is a Windows pseudo-console.

A pseudo-console is a console host without a window: a process attached to it sees the usual console features work (cursor movement, colours, VT escape sequences) while the data it writes can be read from and written to through a pair of pipes. A ConPTY is an io.Reader for the terminal output and an io.Writer for the terminal input, which is what Read and Write implement. See https://learn.microsoft.com/en-us/windows/console/creating-a-pseudoconsole-session

Read, Write and Close may be called concurrently. Resize and Size are safe to call from another goroutine as well.

Example

ExampleConPTY runs a command on a Windows pseudo-console and echoes what it prints, the way a terminal emulator would.

package main

import (
	"io"
	"log"
	"os"

	"golang.org/x/sys/windows"

	"github.com/malivvan/pty"
)

func main() {
	console, err := pty.NewConPTY(pty.DefaultWidth, pty.DefaultHeight, 0)
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = console.Close() }() // Best effort.

	pid, handle, err := console.Spawn("cmd.exe", []string{"cmd.exe", "/c", "echo hello"}, nil)
	if err != nil {
		log.Fatal(err)
	}
	// The process handle belongs to the caller.
	defer func() { _ = windows.CloseHandle(windows.Handle(handle)) }() // Best effort.

	log.Printf("started process %d", pid)

	_, _ = io.Copy(os.Stdout, console)
}

func NewConPTY

func NewConPTY(width, height, flags int) (*ConPTY, error)

NewConPTY creates a pseudo-console of the requested size.

flags is passed to CreatePseudoConsole unchanged; see the Windows documentation for the PSEUDOCONSOLE_* values. A width or height that is zero or negative is replaced by DefaultWidth or DefaultHeight.

func NewConPTYWithPipes

func NewConPTYWithPipes(inPipeRead, inPipeWrite, outPipeRead, outPipeWrite uintptr, width, height, flags int) (*ConPTY, error)

NewConPTYWithPipes creates a pseudo-console driven through the given pipe handles, which must be the four values returned by CreatePipes or four equivalent inheritable pipe handles. Passing existing pipes is useful when the pseudo-console is created for a process that is going to be started elsewhere.

On success the pseudo-console takes ownership of the handles: it closes them from ConPTY.Close. On failure the caller keeps ownership and has to close them itself.

The pseudo-console duplicates the slave ends of the pipes (inPipeRead and outPipeWrite) for every process it hosts, so the caller may close its own copies right after this function returns.

func (*ConPTY) Close

func (c *ConPTY) Close() error

Close shuts the pseudo-console down and releases the pipes it was created with, including the master ends that Read and Write use. Closing a ConPTY more than once is safe and returns the result of the first call.

func (*ConPTY) Command

func (c *ConPTY) Command(name string, args ...string) *Cmd

Command returns a command that runs on the terminal; see Cmd.

func (*ConPTY) CommandContext

func (c *ConPTY) CommandContext(ctx context.Context, name string, args ...string) *Cmd

CommandContext returns a command that runs on the terminal and is stopped when ctx is done. A nil context is a mistake, which Cmd.Start reports as ErrNilContext.

func (*ConPTY) Fd

func (c *ConPTY) Fd() uintptr

Fd returns the handle of the pseudo-console itself, which is not a file descriptor. The handles that carry the terminal data are the ones returned by ConPTY.InPipeWriteFd and ConPTY.OutPipeReadFd.

func (*ConPTY) InPipeReadFd

func (c *ConPTY) InPipeReadFd() uintptr

InPipeReadFd returns the handle of the slave end of the input pipe, from which the pseudo-console reads the terminal input.

func (*ConPTY) InPipeWriteFd

func (c *ConPTY) InPipeWriteFd() uintptr

InPipeWriteFd returns the handle of the master end of the input pipe, to which terminal input is written.

func (*ConPTY) OutPipeReadFd

func (c *ConPTY) OutPipeReadFd() uintptr

OutPipeReadFd returns the handle of the master end of the output pipe, from which the terminal output is read.

func (*ConPTY) OutPipeWriteFd

func (c *ConPTY) OutPipeWriteFd() uintptr

OutPipeWriteFd returns the handle of the slave end of the output pipe, to which the pseudo-console writes the terminal output.

func (*ConPTY) Read

func (c *ConPTY) Read(buf []byte) (n int, err error)

Read reads terminal output from the master end of the output pipe; it implements io.Reader. Keep in mind that a read of a pipe only returns once data is available.

func (*ConPTY) Resize

func (c *ConPTY) Resize(width, height int) error

Resize changes the size of the pseudo-console window. The programs running inside it are notified through the usual console size event; whether they act on it is up to them.

func (*ConPTY) Size

func (c *ConPTY) Size() (width, height int, err error)

Size returns the size the pseudo-console was created with or last resized to.

The error result is always nil; the method returns one so that its signature matches the terminal size helpers of this package.

func (*ConPTY) Spawn

func (c *ConPTY) Spawn(name string, args []string, attr *syscall.ProcAttr) (pid int, handle uintptr, err error)

Spawn starts a process attached to the pseudo-console and returns its process id together with its handle. The caller owns that handle and has to close it with windows.CloseHandle once the process is done.

name is the program to run and args its arguments, in the form os/exec expects: the command line is built from both, unless attr.Sys.CmdLine overrides it. attr may be nil, which means: the current directory, the environment of the current process, and no special creation flags.

func (*ConPTY) Write

func (c *ConPTY) Write(data []byte) (n int, err error)

Write writes terminal input to the master end of the input pipe; it implements io.Writer.

type Terminal

type Terminal interface {
	io.ReadWriteCloser

	// Resize changes the size of the terminal.
	Resize(width, height int) error

	// Size returns the current size of the terminal.
	Size() (width, height int, err error)

	// Command returns a command that runs on the terminal; see [Cmd].
	Command(name string, args ...string) *Cmd

	// CommandContext returns a command that runs on the terminal and is stopped
	// when ctx is done; see [Cmd].
	CommandContext(ctx context.Context, name string, args ...string) *Cmd
}

Terminal is the behaviour of a pseudo-terminal that is driven through a single object rather than through a pair of files.

It is implemented by ConPTY, the real Windows pseudo-console, and by VirtualPTY, the in-memory terminal that works everywhere. A pseudo-terminal created by Open or Start is a pair of *os.File values instead, driven with Read, Write, SetSize and GetSize.

type VirtualPTY

type VirtualPTY struct {
	// contains filtered or unexported fields
}

VirtualPTY is a pseudo-terminal whose two ends live in the same process: it needs neither operating system support nor a child process, so it is available on every system this package builds on, and it lets a program that expects to run on a terminal run inside the process that drives it.

The terminal starts in canonical (cooked) mode and behaves like a real one: the input written with Write is echoed back, it only reaches the hosted program one complete line at a time, the erase and end-of-file characters are processed, and the line feeds the program writes are expanded to carriage return plus line feed on the way back, so a program that writes a carriage return of its own, as Windows programs do, gets two of them. Each of those is what a terminal does; VirtualPTY.SetRaw turns all of it off.

Like a real terminal, it holds a bounded amount of data: a program that writes more than the terminal can hold waits until the terminal is read, and so does a terminal that is typed into faster than the program reads.

Driving a program that runs in the same process

VirtualPTY.Slave returns the end of the terminal the hosted program uses. Handing it to a program that only needs a reader for its input and writers for its output is enough to give that program a terminal, without starting another process. A shell interpreter, such as the one in mvdan.cc/sh/v3, is the classic example:

vt := pty.NewVirtualPTY(80, 24)
defer vt.Close()

runner, err := interp.New(interp.StdIO(vt.Slave(), vt.Slave(), vt.Slave()))
if err != nil {
	return err
}
go runner.Run(ctx, file)

// Type a command on the terminal and read what the shell answers.
vt.Write([]byte("echo hello\n"))
io.Copy(os.Stdout, vt)

The same value can be used as the standard streams of a child process with os/exec, but note that such a process does not get a controlling terminal: it cannot open /dev/tty, read terminal attributes or receive signals from the terminal. Use Open or Start when that matters.

A VirtualPTY is safe for concurrent use by multiple goroutines.

func NewVirtualPTY

func NewVirtualPTY(width, height int) *VirtualPTY

NewVirtualPTY returns a new in-memory pseudo-terminal of the given size. A width or height that is zero or negative is replaced by DefaultWidth or DefaultHeight, as NewConPTY does.

The terminal must be closed with VirtualPTY.Close when it is no longer needed.

func (*VirtualPTY) Close

func (v *VirtualPTY) Close() error

Close ends the terminal: the hosted program still reads the input the terminal had set aside for it and then sees the end of its input, and the terminal still reads the output the program had written; after that, reads of the terminal report io.EOF and writes fail with os.ErrClosed. Closing a terminal more than once is safe.

func (*VirtualPTY) Command

func (v *VirtualPTY) Command(name string, args ...string) *Cmd

Command returns a command that runs on the terminal; see Cmd.

The input of the terminal is shared with the other readers of its program end, so what is typed reaches the command in turn, as it does when several processes read the same terminal. Waiting for the command gives the input back: see Cmd.Wait.

func (*VirtualPTY) CommandContext

func (v *VirtualPTY) CommandContext(ctx context.Context, name string, args ...string) *Cmd

CommandContext returns a command that runs on the terminal and is stopped when ctx is done. A nil context is a mistake, which Cmd.Start reports as ErrNilContext.

func (*VirtualPTY) OnInterrupt

func (v *VirtualPTY) OnInterrupt(handler func())

OnInterrupt registers a handler that is called, in its own goroutine, when the interrupt character (^C) is typed on the terminal. A nil handler removes the current one.

A real terminal delivers a signal to the programs running on it instead; since a virtual terminal hosts no processes, the program driving it is told about the interruption here. Cancelling the context of a shell interpreter, for instance, is what makes it stop the command it is running. Interrupt characters typed in the same call to VirtualPTY.Write are reported as a single interruption.

func (*VirtualPTY) Read

func (v *VirtualPTY) Read(p []byte) (int, error)

Read reads what the hosted program wrote, with the translation a terminal applies to its output: each line feed becomes a carriage return followed by a line feed, unless the terminal is in raw mode.

Read blocks until the program writes something, and returns io.EOF once the program has closed its end of the terminal or the terminal itself is closed.

func (*VirtualPTY) Resize

func (v *VirtualPTY) Resize(width, height int) error

Resize changes the size of the terminal. The size is stored as given, so that a program that asks for a size of zero, which some do to mean "unknown", gets exactly that.

func (*VirtualPTY) SetRaw

func (v *VirtualPTY) SetRaw(raw bool)

SetRaw switches the terminal between raw mode and canonical (cooked) mode, the mode it starts in. In raw mode input is handed to the hosted program byte by byte, without echo, without line buffering and without any translation of the input or the output, which is what a full screen program expects.

What a terminal has typed but not handed over yet when it stops assembling lines is handed to the program right away.

func (*VirtualPTY) Size

func (v *VirtualPTY) Size() (width, height int, err error)

Size returns the size the terminal was created with or last resized to.

The error result is always nil; the method returns one so that its signature matches the other terminals of this package.

func (*VirtualPTY) Slave

func (v *VirtualPTY) Slave() io.ReadWriteCloser

Slave returns the end of the terminal the hosted program uses: what is typed with VirtualPTY.Write is read from it, line by line, and what is written to it is read from the terminal with VirtualPTY.Read.

Like the slave device of a real terminal it is a single end, so closing it ends the input and the output of the program at once. The value belongs to the terminal and stays valid until then; it reports io.EOF for both reads and writes afterwards.

func (*VirtualPTY) Write

func (v *VirtualPTY) Write(p []byte) (int, error)

Write sends input to the terminal, as a user typing on it would. In canonical mode the input is echoed back and only a complete line reaches the hosted program; see VirtualPTY and VirtualPTY.SetRaw.

Write waits while the program has not read the input the terminal holds for it, and while the echo and the output of the program have not been read. It returns os.ErrClosed once the terminal is closed, or once the program has closed its end of it.

type Winsize

type Winsize struct {
	Rows uint16 // Number of rows, in cells (ws_row).
	Cols uint16 // Number of columns, in cells (ws_col).
	X    uint16 // Width in pixels (ws_xpixel).
	Y    uint16 // Height in pixels (ws_ypixel).
}

Winsize describes the size of a terminal, in character cells and in pixels.

Rows and Cols are what terminal applications care about; X and Y are the pixel size and stay zero on terminals that do not report it.

func GetFullSize

func GetFullSize(*os.File) (*Winsize, error)

GetFullSize always fails with ErrUnsupported: the systems this file is built for have no terminal size request. It exists so that portable code keeps compiling.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL