| 🛟 Updated. 28d5985 k33g 19h ago | 1 | //go:build linux |
| 2 | |
| 3 | package terminal |
| 4 | |
| 5 | import ( |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "syscall" |
| 9 | |
| 10 | "golang.org/x/sys/unix" |
| 11 | ) |
| 12 | |
| 13 | // openPTY allocates a pseudo-terminal and returns both of its ends. |
| 14 | // |
| 15 | // Linux hands out the slave by number: unlock the pair, ask which number it |
| 16 | // got, and the device is /dev/pts/<number>. |
| 17 | func openPTY() (master, slave *os.File, err error) { |
| 18 | master, err = os.OpenFile("/dev/ptmx", os.O_RDWR|unix.O_NOCTTY, 0) |
| 19 | if err != nil { |
| 20 | return nil, nil, fmt.Errorf("terminal: opening /dev/ptmx: %w", err) |
| 21 | } |
| 22 | |
| 23 | // A pair starts locked so that nothing can open the slave between its |
| 24 | // creation and the master being ready for it. |
| 25 | if err := unix.IoctlSetPointerInt(int(master.Fd()), unix.TIOCSPTLCK, 0); err != nil { |
| 26 | master.Close() |
| 27 | return nil, nil, fmt.Errorf("terminal: unlocking the pseudo-terminal: %w", err) |
| 28 | } |
| 29 | |
| 30 | number, err := unix.IoctlGetInt(int(master.Fd()), unix.TIOCGPTN) |
| 31 | if err != nil { |
| 32 | master.Close() |
| 33 | return nil, nil, fmt.Errorf("terminal: naming the pseudo-terminal: %w", err) |
| 34 | } |
| 35 | |
| 36 | slave, err = os.OpenFile(fmt.Sprintf("/dev/pts/%d", number), os.O_RDWR|unix.O_NOCTTY, 0) |
| 37 | if err != nil { |
| 38 | master.Close() |
| 39 | return nil, nil, fmt.Errorf("terminal: opening the slave side: %w", err) |
| 40 | } |
| 41 | return master, slave, nil |
| 42 | } |
| 43 | |
| 44 | // setWinsize tells the pseudo-terminal how big it is, which the kernel passes |
| 45 | // on to the shell as SIGWINCH. |
| 46 | func setWinsize(master *os.File, width, height int) error { |
| 47 | return unix.IoctlSetWinsize(int(master.Fd()), unix.TIOCSWINSZ, &unix.Winsize{ |
| 48 | Row: uint16(height), |
| 49 | Col: uint16(width), |
| 50 | }) |
| 51 | } |
| 52 | |
| 53 | // childAttributes put the shell in a session of its own with the slave as its |
| 54 | // controlling terminal. |
| 55 | // |
| 56 | // Without this the shell has no controlling terminal, and job control — Ctrl-C, |
| 57 | // Ctrl-Z, running something in the background — does not work at all. |
| 58 | func childAttributes() *syscall.SysProcAttr { |
| 59 | return &syscall.SysProcAttr{Setsid: true, Setctty: true} |
| 60 | } |