duangang4001
duangang4001
2016-02-28 02:22

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

  • signals
  • linux
  • windows

I am trying to build a chatroom application in go and I want to call logout function when client uses ctrl+c or presses close buttom of the terminal.
I tried methods given here and here but they were not capturing any signals(tried in Windows 10 and Fedora 23). Here is my code snippet,

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()
}()

I have some other functions running concurrently using goroutine, is it the reason behind this function not capturing any signals?

Any help would be appreciated.

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答