如何退出 reader.ReadString 等待用户输入的状态?

huangapple go评论71阅读模式
英文:

How can I exit reader.ReadString from waiting for user input?

问题

我正在做的是,当按下CTRL-C时,它停止要求输入。

目前我有的是,一个单独的go协程,在接收到CTRL-C时,改变一个变量的值,这样它就不会再要求输入另一行了。然而,我似乎找不到绕过当前行的方法。

也就是说,我仍然需要按一次回车键,才能退出当前的读取\n的迭代。

也许有一种方法可以将"\n"推送到stdin,以便reader.ReadString读取。或者有一种完全停止其执行的方法。

英文:

I am making it so that it stops asking for input upon CTRL-C.

What I have currently is that a separate go-routine, upon receiving a CTRL-C, changes the value of a variable so it won't ask for another line. However, I can't seem to find a way around the current line.

i.e. I still have to press enter once, to get out of the current iteration of reading for \n.

Is there perhaps a way to push a "\n" into stdin for the reader.ReadString to read. Or a way to stop its execution altogether.

答案1

得分: 2

Go语言提供的唯一可靠的机制是select,而select只能选择通道读取,因此你的唯一选择是将信号处理的goroutine更改为向通道写入,并添加另一个goroutine来处理stdin并将输入行传递给通道,然后在这两个通道上进行选择。

然而,这仍然没有完全回答你的问题:主程序可以在按下Ctrl-C后停止等待输入,但读取输入的goroutine仍然会等待输入。在某些情况下,这可能是可以接受的...如果你永远不需要再次使用stdin,或者如果你将立即以完全相同的方式处理行。但是,如果你想要做一些与ReadString不同的操作,你就会陷入困境。我唯一看到的解决方案是编写自己的状态机,围绕ReadReadByte,以便能够根据外部条件改变其行为,但这很容易变得非常复杂。

基本上,这看起来是Go相对于底层系统简化了事情(不暴露任何类似于EINTR的东西,不允许在文件句柄上进行选择),但最终为程序员提供了更少的控制权。

英文:

The only decent mechanism that Go gives you to proceed when either of two things happens is select, and select only selects on channel reads, so your only option is to change your signal-handler goroutine to write to a channel, and add another goroutine that handles stdin and passes lines of input to a channel, then select on the two channels.

However, that still leaves your question half-unanswered: your main program can stop waiting for input on a Ctrl-C, but the goroutine that's reading input will still be waiting for input. In some cases that might be okay... if you will never need stdin again, or if you will go right back to processing lines in the same exact way. But if you want to do something other than ReadString from that reader, you're stuck... literally. The only solution I see would be to write your own state machine around Read or ReadByte that is capable of changing its behavior in response to external conditions, but that can easily get horribly complicated.

Basically, this looks like a case where Go simplifies things compared to the underlying system (not exposing anything like EINTR, not allowing select on filehandles), but ends up providing less power to the programmer.

huangapple
  • 本文由 发表于 2016年4月23日 05:03:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/36803268.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定