Prevent ^C from being displayed on Ctrl+C in Go

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

Prevent ^C from being displayed on Ctrl+C in Go

问题

我想要在按下Ctrl+C时阻止“^C”被输出到终端。

我是这样捕获中断命令的:

c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, syscall.SIGTERM)
go func() {
	<-c
	// 在这里处理退出代码
}()

... 然而,当我按下Ctrl+C时,"^C"会被输出到终端。这并不理想。

英文:

I'd like to prevent "^C" from being outputted to the terminal when Ctrl+C is pressed.

I'm capturing the interrupt command like this:

c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, syscall.SIGTERM)
go func() {
	&lt;-c
	// exit code here
}()

... however, when I press Ctrl+C, "^C" is outputted into the terminal. This isn't ideal.

答案1

得分: 8

如果你之后要打印一些内容,你可以这样做:

fmt.Print("\r")
log.Println("Shutting down")

\r 是一个回车字符;它告诉你的终端模拟器将光标移动到行的开头。这样你就可以覆盖终端上的 ^C

英文:

If you print something afterwards, you can do

fmt.Print(&quot;\r&quot;)
log.Println(&quot;Shutting down&quot;)

\r is a carriage return character; it tells your terminal emulator to move the cursor at the start of the line. This way you can overwrite the ^C on the terminal.

答案2

得分: 1

如果将终端设置为原始模式,你将直接获取按键输入,终端不会解释它们(也不会显示^C)。

我不确定在Go语言中设置原始模式的最佳方法,但是golang.org/x/crypto/ssh/terminal的RawMode()函数可以实现。然后,你需要启用INT和TERM处理,否则你将接收到^C作为输入,而不是将其作为中断进行处理。

关于原始模式的解释可以在这里找到:https://unix.stackexchange.com/questions/21752/what-s-the-difference-between-a-raw-and-a-cooked-device-driver

类似的答案可以在这里找到:https://superuser.com/questions/147013/how-to-disable-c-from-being-echoed-on-linux-on-ctrl-c

英文:

If you put the terminal into raw mode, you'll get the keystrokes directly and the tty won't interpret them (and display ^C).

I'm not sure of the best way to set raw mode in Go, but golang.org/x/crypto/ssh/terminal's RawMode() does it. You would then have to enable INT and TERM handling otherwise you'll receive a ^C as input, instead having it be processed as an interruption.

An explanation of raw mode is here: https://unix.stackexchange.com/questions/21752/what-s-the-difference-between-a-raw-and-a-cooked-device-driver

A similar answer is here: https://superuser.com/questions/147013/how-to-disable-c-from-being-echoed-on-linux-on-ctrl-c

huangapple
  • 本文由 发表于 2015年12月20日 02:24:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/34373933.html
匿名

发表评论

匿名网友

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

确定