进程退出信号监听通用程序
用于服务程序监听退出信号,进行优雅的退出,在退出时进行退出处理。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func WaitClose(handler func()) {
defer handler()
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT) //其中 SIGKILL = kill -9 <pid> 可能无法截获
for {
s := <-c
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
time.Sleep(time.Second)
return
case syscall.SIGHUP:
continue
default:
return
}
}
}
handler退出处理函数,用于退出时进行的操作。
This post is licensed under CC BY 4.0 by the author.