標籤:fun for ctr sel signal group sys ctrl job
執行個體
package mainimport( "fmt" "os" "os/signal" "sync" "syscall" "time")func worker(stop <-chan bool) { for { select { case <-stop: fmt.Println("exit") return default: fmt.Println("running...") time.Sleep(3) } }}func main() { stop := make(chan bool) var wg sync.WaitGroup for i := 0; i < 3; i++ { wg.Add(1) go func(stop <-chan bool) { defer wg.Done() worker(stop) }(stop) } waitForSignal() close(stop) fmt.Println("stopping all job") wg.Wait()}func waitForSignal() { sigs := make(chan os.Signal) signal.Notify(sigs, os.Interrupt) signal.Notify(sigs, syscall.SIGTERM) fmt.Println(<-sigs)}
運行結果
pkill訊號syscall.SIGTERM
... running... running... running... running... terminated running... running... stopping all job exit exit exit
或者ctrl+c訊號os.Interrupt
running...interruptstopping all jobrunning...exitexitexit
Go語言-訊號os.Interrupt和訊號syscall.SIGTERM的應用