记录 golang 信号处理
系统信号处理的方式,纯内置的处理。
逻辑是定义一个容量为 1 的 chan 接收系统信号(os.Signal),触发指定信号时往 chan 接收到值,以此判断做相应的处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| package main
import ( "fmt" "os" "os/signal" "syscall" "time" )
func main() { var code = 1 var sc = make(chan os.Signal, 1) signal.Notify(sc, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
ticker := time.NewTicker(time.Second * 1) go func() { for { <-ticker.C fmt.Printf(" ++> working time: %v\n", time.Now().Format("2006-01-02 15:04:05.000")) } }()
LOOP: for { sig := <-sc fmt.Println("recevived signal:", sig.String()) switch sig { case syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT: code = 0 break LOOP case syscall.SIGHUP: fmt.Println("==> reload config") default: break LOOP } }
fmt.Println("==> server exit") os.Exit(code) }
|