我正在尝试在 go 中构建一个聊天室应用程序,我想在客户端使用 ctrl+c 或按下终端的关闭按钮时调用注销功能。
我尝试了给出的方法 here和 here但他们没有捕获任何信号(在 Windows 10 和 Fedora 23 中尝试过)。这是我的代码片段,
sigc := make(chan os.Signal, 1)
signal.Notify(sigc,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT)
go func() {
_ = <-sigc
fmt.Println("ctrl+c pressed")
client.Logout()
}()
我有一些其他的函数使用 goroutine 同时运行,这是这个函数没有捕获任何信号的原因吗?
如有任何帮助,我们将不胜感激。
最佳答案
根据 os.Signal
上的文档,应该可以在 Windows 上捕获中断:https://golang.org/pkg/os/signal/#hdr-Windows .不过,我还没有亲自测试过。
我怀疑你的问题是你应该只使用从 os
导入的信号,例如 os.Interrupt
,而不是 syscall
。
来自 https://golang.org/pkg/os/#Signal :
The only signal values guaranteed to be present on all systems are Interrupt (send the process an interrupt) and Kill (force the process to exit).
来自https://golang.org/pkg/syscall/#pkg-overview :
The primary use of syscall is inside other packages that provide a more portable interface to the system, such as "os", "time" and "net". Use those packages rather than this one if you can.
因此,更改您的 signal.Notify
调用以仅捕获 os.Interrupt
信号。
关于linux - 使用 golang 在 windows 和 linux 中捕获 ctrl+c 或任何其他进程终止信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35677972/