golang unix.TCGETS在Mac上等效



在Linux上,我使用以下代码来启用和禁用控制台回声:

unix.IoctlGetTermios(int(os.Stdin.Fd()), unix.TCGETS)
unix.IoctlSetTermios(unix.Stdout, unix.TCSETS, term)

但是它不能在Mac上编译,我应该在Mac上使用什么?

您可以在Mac OS中使用TIOCGETATIOCSETA

// IoctlSetTermios performs an ioctl on fd with a *Termios.
//
// The req value will usually be TCSETA or TIOCSETA.
func IoctlSetTermios(fd int, req uint, value *Termios) error {
import (
"bufio"
"fmt"
"log"
"os"
"golang.org/x/sys/unix"
)
func main() {
STDIN := int(os.Stdin.Fd())
tio, err := unix.IoctlGetTermios(STDIN, unix.TIOCGETA)
if err != nil {
log.Fatal(err)
}
fmt.Println("Input sth:")
tio.Lflag &^= unix.ECHO
err = unix.IoctlSetTermios(STDIN, unix.TIOCSETA, tio)
if err != nil {
log.Fatal(err)
}
reader := bufio.NewReader(os.Stdin)
line, _ := reader.ReadString('n')
tio.Lflag |= unix.ECHO
err = unix.IoctlSetTermios(STDIN, unix.TIOCSETA, tio)
if err != nil {
log.Fatal(err)
}
fmt.Println(line)
}

代替使用unix.TCGETS/unix.TIOCGETAunix.TCSETS/unix.TIOCSETA,您可以在不同的文件中定义常量,然后使用构建约束来基于操作系统构建这些文件。

你可以在这里查看github.com/moby/term是如何做到的:

https://github.com/moby/term/blob/c43b287e0e0f2460e4ba913936af2f6bdcbe9ed5/termios_bsd.gohttps://github.com/moby/term/blob/c43b287e0e0f2460e4ba913936af2f6bdcbe9ed5/termios_nonbsd.go

使用此方法,您的代码与操作系统解耦,并且您可以始终使用相同的常量。

最新更新