The tty and termios in Go

Skip to first unread message


Feb 7, 2010, 2:44:03 AM2/7/10
to golang-nuts
I've spent this evening trying to use glib's 'termios' in Go without
having to resort to cgo. Fortunately, it wasn't nearly as hard as I
thought. 'termios' is a very simple library and one can perform its
function using existing Go libraries. Specifically: the system call
SYS_IOCTL. 'termios' uses 'ioctl' to read and write tty settings, so
it is not difficult to implement equivalents to those functions.

When I say that I have implemented 'termios', all I mean is that I
ported the 'termios' structure and related constants, and I used
'ioctl' to set and get tty settings rather than 'tcgetattr' and
'tcsetattr'. Here is the C code snippet that I ported to Go:

Here is my port:

This opens the door to password masking and perhaps even ncurses-like
libraries that do not rely on writing cgo bindings to existing C


Ray Hollett

Feb 15, 2010, 10:36:32 AM2/15/10
to golang-nuts
I tried your code using the Go 8g compiler and it worked fine.

Some time ago there was a discussion about using exec.Run("/bin/
stty", ...) for providing a similar function. I used this approach
for a simple bash like command editing facility. However, I was
concerned about portability. Ian Lance Taylor suggested using termios
and made some very good points about Windows portability. I have
copied his input below for reference as I assume that it is just as
relevant to your termios approach:

>Everything in the area of terminal control is unportable. I took a
>quick look at Tcl, which tries pretty hard to be portable across
>operating systems, but it doesn't appear to handle this either.
>The POSIX termios interface is pretty widely available on Unix systems
>these days, thank goodness. However, it is a poor match for Windows.
>Termios is used to control the command line, pseudo-terminals, and
>serial ports, which are all different things on Windows. For echo the
>relevant case here is what Windows call the console, but there is no
>exact mapping between termios options and console options (e.g.,
>termios separates raw-mode from echo-mode, but Windows does not).
>Perhaps the Unix syscall interface should add Termios, Tcsetattr, and
>friends, and the Windows syscall interface should add SetConsoleMode.
>Then somebody can think about a higher level package which provides
>simple functions like turning off echo, and has different
>implementations on Unix and Windows.


Feb 15, 2010, 11:05:54 AM2/15/10
to golang-nuts
Yes, I followed that discussion and know that what I have produced is
not portable. I simply posted my approach as one that relies entirely
on syscalls, as opposed to binding to libraries via cgo or running
other processes via exec.Run. Lately I have been trying to avoid cgo
entirely, so in a way this was an exercise for myself, but I do feel
that it has practical purposes, too.


Reply all
Reply to author
0 new messages