0

I am searching for a cross-platform way to access the controlling terminal in Go:

On unix I can open /dev/tty:

tty, err := os.OpenFile("/dev/tty", os.O_RDONLY, 0)

and read from tty.

How can read from the controlling terminal in Windows?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Gabriel
  • 8,990
  • 6
  • 57
  • 101
  • Windows does not have the concept of the terminal in the same sense Unix has, and neither does it have the concept of job control (and hence foreground and background processes—with relation to the controlling terminal). Windows's console emulates the command prompt of MS-DOS and hence it's by definition a single-process no-nothing setup. But the real question is: what problem are you trying to solve? I mean, it looks like the manifestation of an [XY problem](https://meta.stackexchange.com/questions/66377). – kostix Oct 10 '20 at 17:54
  • Let me elaborate so that my response does not sound glib: a process running on a terminal/console normally has its [standard input stream](https://en.wikipedia.org/wiki/Standard_streams) connected to the terminal, so there's no need to do any dances to "read from the controlling terminal"—just read from `os.Stdin` _and handle any errors_ while doing this. If you need to be able to muck with the terminal (switch its modes etc), that is completely another story, and it's not going to be cross-platform out of the box. So we need a more narrow problem statement to try to help you. – kostix Oct 10 '20 at 17:57
  • I am rewriting a hook manager and implementing a prompt when the hook is run by git. And it would be good to know, if there is a way to obtain the "controlling" terminal when the hook is run by git on Windows. When the hook is run from git, stdin does normaly (hook specfific) not get connected to the terminal on unix, . So I cannot just read from `os.Stdin`. https://github.com/gabyx/githooks/blob/feature/go-refactoring/githooks/common/prompt.go#L109 – Gabriel Oct 10 '20 at 19:27
  • 1
    OK, I think I understand. You might need to perform som encantation to try to attach to the console of the parent process as explained [here](https://stackoverflow.com/a/23744350/720999), and then maybe set `os.Stdin` to the result of a call to `os.NewFile` on the handle obtained by one of the console allocation calls. Also note that you might need to ask folks behind GfW on [their mailing list](https://groups.google.com/forum/#!forum/git-for-windows/) about this issue: I'm inclined to think it may be more weird on Windows that it might seem on the first glance. – kostix Oct 12 '20 at 08:29

0 Answers0