linux - 使用 golang 在 windows 和 linux 中捕获 ctrl+c 或任何其他进程终止信号

标签 linux windows go signals

我正在尝试在 go 中构建一个聊天室应用程序,我想在客户端使用 ctrl+c 或按下终端的关闭按钮时调用注销功能。
我尝试了给出的方法 herehere但他们没有捕获任何信号(在 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/

相关文章:

c++ - Windows下如何为Code::Blocks/MinGW32编译Box2D?

go - 去处理所有返回的错误是惯用的吗?

linux - 保留一对中的一个成员

python - 如何在不中断音乐/其他声音播放的情况下在 Python 中播放声音

php - 在 Linux 中的 PHP 和 C 可执行文件之间传递数据

c++ - 如何在 C++ 中获得屏幕分辨率?

Windows 与 Sony Camera Remote API 的兼容性

linux - 使用Linux shell脚本在文件名中插入文本

go - 在golang中一键解码多种数据类型

docker - main.go :11:8: package aerospike_shared is not in GOROOT (/usr/local/go/src/aerospike_shared)