不用多说,直接上代码
package main
import (
"os"
"os/signal"
"time"
"syscall"
"fmt"
)
var onlyOneSignalHandler = make(chan struct{})
var shutdownSignals = []os.Signal{os.Interrupt, syscall.SIGTERM}
// SetupSignalHandler registered for SIGTERM and SIGINT. A stop channel is returned
// which is closed on one of these signals. If a second signal is caught, the program
// is terminated with exit code 1.
func SetupSignalHandler() (stopCh <-chan struct{}) {
close(onlyOneSignalHandler) // panics when called twice
stop := make(chan struct{})
c := make(chan os.Signal, 2) //2表示chan的长度,输入多少次,就可以实现Control+c执行动作多少次
signal.Notify(c, shutdownSignals...)
go func() {
<-c
fmt.Println("第一次Control+c退出...")
close(stop)
<-c
fmt.Println("第二次Control+c退出....")
os.Exit(1) // second signal. Exit directly.
}()
return stop
}
func Demo(stopCh <-chan struct{}){
go func() {
<-stopCh
}()
}
func main(){
Demo(SetupSignalHandler())
time.Sleep(1*time.Hour)
}
运行结果:
➜ test go run signal.go
^C第一次Control+c退出...
^C第二次Control+c退出....
exit status 1