2
[Golang] Capture and Handle Ctrl+C Event
source link: http://siongui.github.io/2015/03/11/go-ctrl-c-handler/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
For database programs, we need to close the database if users press Ctrl+C to terminate the program. This post shows how to capture Ctrl+C event and run the handler in Go.
Souce Code
ctrl+c.go | repository | view raw
// http://stackoverflow.com/questions/11268943/golang-is-it-possible-to-capture-a-ctrlc-signal-and-run-a-cleanup-function-in // https://gobyexample.com/signals package main import ( "os" "os/signal" "syscall" "fmt" ) func handleCtrlC(c chan os.Signal) { sig := <-c // handle ctrl+c event here // for example, close database fmt.Println("\nsignal: ", sig) os.Exit(0) } func main() { c := make(chan os.Signal) signal.Notify(c, os.Interrupt, syscall.SIGTERM) go handleCtrlC(c) // block here for { select {} } }
Tested on: Ubuntu Linux 14.10, Go 1.4.
References:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK