duangang4001 2016-02-28 02:22
浏览 476
已采纳

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

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条回答 默认 最新

  • doucan8521 2016-02-28 14:13
    关注

    According to the docs on os.Signal, it should be possible to catch interrupts on Windows: https://golang.org/pkg/os/signal/#hdr-Windows. I haven't tested this personally, though.

    I suspect your problem is that you should only use signals imported from os, such as os.Interrupt, instead of syscall.

    From 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).

    And from 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.

    So, change your signal.Notify call to catch only the os.Interrupt signal.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 vb net 使用 sendMessage 如何输入鼠标坐标
  • ¥200 求能开发抖音自动回复卡片的软件
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!
  • ¥20 有关esp8266连接阿里云
  • ¥15 C# 调用Bartender打印机打印
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题
  • ¥50 C#编程中使用printDocument类实现文字排版打印问题
  • ¥15 找会编程的帅哥美女 可以用MATLAB里面的simulink编程,用Keil5编也可以。