1. 程式人生 > >golang捕獲control+c功能實現

golang捕獲control+c功能實現

不用多說,直接上程式碼

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