Graceful Exit
func Notify(c chan<- os.Signal, sig ...os.Signal)
Notify causes package signal to relay incoming signals to c. If no signals are provided, all incoming signals will be relayed to c. Otherwise, just the provided signals will.
Package signal will not block sending to c: the caller must ensure that c has sufficient buffer space to keep up with the expected signal rate. For a channel used for notification of just one signal value, a buffer of size 1 is sufficient.
It is allowed to call Notify multiple times with the same channel: each call expands the set of signals sent to that channel. The only way to remove signals from the set is to call Stop.
It is allowed to call Notify multiple times with different channels and the same signals: each channel receives copies of incoming signals independently.
Demo
Demo1
package main
import (
"fmt"
"os"
"os/signal"
)
func main() {
// Set up channel on which to send signal notifications.
// We must use a buffered channel or risk missing the signal
// if we're not ready to receive when the signal is sent.
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
// Block until a signal is received.
s := <-c
fmt.Println("Got signal:", s)
}
Demo2
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
)
func main() {
sigs := make(chan os.Signal, 1)
done := make(chan bool, 1)
// When we run this program it will block waiting for a signal. By typing ctrl-C (which the terminal shows as ^C) we can send a SIGINT signal, causing the program to print interrupt and then exit.
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigs
fmt.Println()
fmt.Println(sig)
done <- true
}()
fmt.Println("awaiting signal")
<-done
fmt.Println("exiting")
}
$ go run signals.go
awaiting signal
^C
interrupt
exiting
Reference
- https://gobyexample.com/signals
- https://callistaenterprise.se/blogg/teknik/2019/10/05/go-worker-cancellation/
- https://grisha.org/blog/2014/06/03/graceful-restart-in-golang/
- https://colobu.com/2015/10/09/Linux-Signals/
- https://studygolang.com/articles/19990
- https://learnku.com/articles/23505/graceful-restart
- http://kuangchanglang.com/golang/2017/04/27/golang-graceful-restart