Skip to content

Instantly share code, notes, and snippets.

@duguying
Created December 15, 2016 07:02
Show Gist options
  • Save duguying/46342d9d2845fddab3f038670dafe16b to your computer and use it in GitHub Desktop.
Save duguying/46342d9d2845fddab3f038670dafe16b to your computer and use it in GitHub Desktop.
程序接收退出信号安全退出
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
)
func main() {
mainExitChan := make(chan int, 2)
installSignal(mainExitChan)
<-mainExitChan
fmt.Println("exit")
}
func installSignal(mainExitChan chan int) {
signalChan := make(chan os.Signal, 1)
signalIgnoreChan := make(chan os.Signal, 1)
go func() {
for {
select {
case <-signalChan:
mainExitChan <- 1
return
case <-signalIgnoreChan:
continue
}
}
}()
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
signal.Notify(signalIgnoreChan, syscall.SIGPIPE)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment