4

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.

Community
  • 1
  • 1
Vishwasa Navada K
  • 572
  • 1
  • 8
  • 30
  • That captures signals just fine on unix, so you need to show the accompanying code. I'm not really familiar with windows, with IIRC you can't catch ctrl+c as a signal and it has to be handled by the terminal. – JimB Feb 28 '16 at 02:57
  • @JimB rest of the code can be viewed [here](https://github.com/GOOFS/go-goof-Talk/blob/master/client/client.go). But that does not have the code snippet I mentioned above. – Vishwasa Navada K Feb 28 '16 at 03:17

1 Answers1

7

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.

ford
  • 10,687
  • 3
  • 47
  • 54
  • 1
    Thanks for the detailed answer and documentation quotes. I also found that one more go routine was clashing with it and changing the order of function call also helped me to resolve this. – Vishwasa Navada K Feb 28 '16 at 16:21
  • Thanks for the question and answer. Couldn't figure out why my code was not catching `SIGINT` - putting the goroutine that catches as the very first code in `main` did the trick – ddrake12 Jun 14 '19 at 03:42