//go:build linux package terminal import ( "fmt" "os" "syscall" "golang.org/x/sys/unix" ) // openPTY allocates a pseudo-terminal and returns both of its ends. // // Linux hands out the slave by number: unlock the pair, ask which number it // got, and the device is /dev/pts/. func openPTY() (master, slave *os.File, err error) { master, err = os.OpenFile("/dev/ptmx", os.O_RDWR|unix.O_NOCTTY, 0) if err != nil { return nil, nil, fmt.Errorf("terminal: opening /dev/ptmx: %w", err) } // A pair starts locked so that nothing can open the slave between its // creation and the master being ready for it. if err := unix.IoctlSetPointerInt(int(master.Fd()), unix.TIOCSPTLCK, 0); err != nil { master.Close() return nil, nil, fmt.Errorf("terminal: unlocking the pseudo-terminal: %w", err) } number, err := unix.IoctlGetInt(int(master.Fd()), unix.TIOCGPTN) if err != nil { master.Close() return nil, nil, fmt.Errorf("terminal: naming the pseudo-terminal: %w", err) } slave, err = os.OpenFile(fmt.Sprintf("/dev/pts/%d", number), os.O_RDWR|unix.O_NOCTTY, 0) if err != nil { master.Close() return nil, nil, fmt.Errorf("terminal: opening the slave side: %w", err) } return master, slave, nil } // setWinsize tells the pseudo-terminal how big it is, which the kernel passes // on to the shell as SIGWINCH. func setWinsize(master *os.File, width, height int) error { return unix.IoctlSetWinsize(int(master.Fd()), unix.TIOCSWINSZ, &unix.Winsize{ Row: uint16(height), Col: uint16(width), }) } // childAttributes put the shell in a session of its own with the slave as its // controlling terminal. // // Without this the shell has no controlling terminal, and job control — Ctrl-C, // Ctrl-Z, running something in the background — does not work at all. func childAttributes() *syscall.SysProcAttr { return &syscall.SysProcAttr{Setsid: true, Setctty: true} }