
The signals example is overly complex, involving an unneeded go routine and an additional signal. This creates indirection making the code hard to understand. The proposed change simplifies the code by removing the go routine and the additional signal, leaving the fundamental concept.
39 lines
1.0 KiB
Go
39 lines
1.0 KiB
Go
// Sometimes we'd like our Go programs to intelligently
|
|
// handle [Unix signals](http://en.wikipedia.org/wiki/Unix_signal).
|
|
// For example, we might want a server to gracefully
|
|
// shutdown when it receives a `SIGTERM`, or a command-line
|
|
// tool to stop processing input if it receives a `SIGINT`.
|
|
// Here's how to handle signals in Go with channels.
|
|
|
|
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
)
|
|
|
|
func main() {
|
|
|
|
// Go signal notification works by sending `os.Signal`
|
|
// values on a channel. We'll create a channel to
|
|
// receive these notifications.
|
|
// **Note** that this channel is "buffered".
|
|
sigs := make(chan os.Signal, 1)
|
|
|
|
// `signal.Notify` registers the given channel to
|
|
// receive notifications of the specified signals.
|
|
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
|
|
|
|
fmt.Println("awaiting signal")
|
|
|
|
// Because the `sigs` channel is buffered, the program
|
|
// will wait here until it gets the expected signal and
|
|
// then exit.
|
|
sig := <-sigs
|
|
fmt.Println()
|
|
fmt.Println(sig)
|
|
fmt.Println("exiting")
|
|
}
|