Sometimes we’d like our Go programs to intelligently
handle Unix signals.
For example, we might want a server to gracefully
shutdown when it receives a |
|
![]() ![]() package main |
|
import ( "fmt" "os" "os/signal" "syscall" ) |
|
func main() { |
|
Go signal notification works by sending |
sigs := make(chan os.Signal, 1) |
|
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) |
We could receive from |
done := make(chan bool, 1) |
This goroutine executes a blocking receive for signals. When it gets one it’ll print it out and then notify the program that it can finish. |
go func() { |
sig := <-sigs fmt.Println() fmt.Println(sig) done <- true }() |
|
The program will wait here until it gets the
expected signal (as indicated by the goroutine
above sending a value on |
fmt.Println("awaiting signal") <-done fmt.Println("exiting") } |
When we run this program it will block waiting for a
signal. By typing |
$ go run signals.go awaiting signal ^C interrupt exiting |
Next example: Exit.