You can get notify about signals the os sends to your process.
For example, Ctrl-C
sends SIGINT
signal. Here's how to get notified about SIGINT
signal:
package main
import (
"fmt"
"os"
"os/signal"
)
func main() {
sigChan := make(chan os.Signal)
// assign all signal notifications to the channel
signal.Notify(sigChan)
// 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, uses signal.Notify
to tell Go runtime to send a message to the channel when the OS sends a signal to the process.
$ go run signals.go
^CReceived signal from OS: interrupt
The ^C
above is the keyboard command CTRL+C
which sends the SIGINT
signal.