OS Signals
suggest changeYou can get notified about signals the OS sends to your process.
For example, Ctrl-C sends a SIGINT signal. Here's how to get notified about that signal:
package main
import (
"fmt"
"os"
"os/signal"
)
func main() {
sigChan := make(chan os.Signal, 1)
// relay interrupt notifications to the channel
signal.Notify(sigChan, os.Interrupt)
// blocks until you get a signal from the OS
select {
case sig := <-sigChan:
fmt.Println("Received signal from OS:", sig)
}
}
This program creates a channel and uses signal.Notify to tell the Go runtime to send os.Interrupt on that channel when the OS sends the process an interrupt. The channel is buffered so the runtime does not drop the signal if the receive is not yet waiting.
$ go run signals.go
^CReceived signal from OS: interrupt
The ^C above is the keyboard command CTRL+C which sends the SIGINT signal.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents