演示
go 通过管道chan和os.Signal终止程序的方法
func mian() {
done := make(chan bool, 1)
//程序中向done chan中写入值也可以终止。
wg := &sync.WaitGroup{}
wg.Add(1)
handleShutdown(done, wg)
wg.Wait()
time.Sleep(time.Second)
}
func handleShutdown(done chan bool, wg *sync.WaitGroup) {
ch := make(chan os.Signal, 1)
go func() {
for {
select {
case <-done:
wg.Done()
return
case <-ch:
log.Println("ctrl+c interrupt received")
close(done)
wg.Done()
return
}
}
}()
signal.Notify(ch, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
}