| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "os" |
| 5 | "syscall" |
| 6 | "unsafe" |
| 7 | ) |
| 8 | |
| 9 | // ttyState is the controlling terminal's settings, saved so they can be |
| 10 | // put back after a program that changes them is stopped before it could. |
| 11 | type ttyState struct { |
| 12 | f *os.File |
| 13 | t syscall.Termios |
| 14 | } |
| 15 | |
| 16 | // ttyPath is the controlling terminal. Tests name a pty of their own. |
| 17 | var ttyPath = "/dev/tty" |
| 18 | |
| 19 | // saveTerminal saves the controlling terminal's settings, or returns nil |
| 20 | // when there is no terminal to read. |
| 21 | func saveTerminal() *ttyState { |
| 22 | f, err := os.OpenFile(ttyPath, os.O_RDWR|syscall.O_NOCTTY, 0) |
| 23 | if err != nil { |
| 24 | return nil |
| 25 | } |
| 26 | s := &ttyState{f: f} |
| 27 | if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), uintptr(syscall.TCGETS), uintptr(unsafe.Pointer(&s.t))); errno != 0 { |
| 28 | f.Close() |
| 29 | return nil |
| 30 | } |
| 31 | return s |
| 32 | } |
| 33 | |
| 34 | // restore puts the saved settings back when the terminal's differ from |
| 35 | // them. Settings left as they were are not written again, so a process in |
| 36 | // the background is not stopped for writing them. |
| 37 | func (s *ttyState) restore() { |
| 38 | if s == nil { |
| 39 | return |
| 40 | } |
| 41 | var now syscall.Termios |
| 42 | if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, s.f.Fd(), uintptr(syscall.TCGETS), uintptr(unsafe.Pointer(&now))); errno == 0 && now == s.t { |
| 43 | return |
| 44 | } |
| 45 | syscall.Syscall(syscall.SYS_IOCTL, s.f.Fd(), uintptr(syscall.TCSETS), uintptr(unsafe.Pointer(&s.t))) |
| 46 | } |
| 47 | |
| 48 | // release lets the terminal go. |
| 49 | func (s *ttyState) release() { |
| 50 | if s != nil { |
| 51 | s.f.Close() |
| 52 | } |
| 53 | } |