How to make golang signal handler working on windows

Viewed 46

The following test program is working fine on my linux machine, but it is not working on my windows machine

package main

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"
    "time"
)

func main() {
    detectShutdown()
    fmt.Println("Running")
    time.Sleep(5 * time.Second)
}

func detectShutdown() {
    sigChan := make(chan os.Signal, 1)
    signal.Notify(sigChan, syscall.SIGINT)
    go func() {
        sig := <-sigChan
        fmt.Printf("Signal [%s] detected\n", sig)
        os.Exit(1)
    }()
}

Output on linux

Running
^CSignal [interrupt] detected

Output on Windows

Running

Anyone has idea on how to make it works on Windows? Thanks

1 Answers

The problem is that Windows does not have POSIX (Unix) signals as a form of supported IPC. Handling Ctrl-C (and Ctrl-Break) keyboard combinations in console applications is done completely different on Windows than it is done in programs running attached to Unix-compatible terminals and terminal emulators.

Since some time Go has gained support in os/signal for Windows in the form of a special signal os.Interrupt, which, on POSIX-compatible systems is an alias for os.SIGINT (and is processed in the usual way), and on Windows it does not stand for any signal (for their lack thereof) but is emulated when the user presses the keyboard combinations mentioned above.

I advise you to actually read the docs of the os/signal package—especially its section called "Windows". Doing this up-front would have saved you and me spending time asking and answering a question about a non-problem.

Related