Last active
May 18, 2016 20:57
-
-
Save husobee/531062f48f7f35688e7e4c63139a9616 to your computer and use it in GitHub Desktop.
handle signals golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"os/signal" | |
"syscall" | |
"time" | |
) | |
func main() { | |
var returnCode = make(chan int) | |
var finishUP = make(chan struct{}) | |
var done = make(chan struct{}) | |
var gracefulStop = make(chan os.Signal) | |
signal.Notify(gracefulStop, syscall.SIGTERM) | |
signal.Notify(gracefulStop, syscall.SIGINT) | |
go func() { | |
// wait for our os signal to stop the app | |
// on the graceful stop channel | |
sig := <-gracefulStop | |
fmt.Printf("caught sig: %+v", sig) | |
// send message on "finish up" channel to tell the app to | |
// gracefully shutdown | |
finishUP<-struct{}{} | |
// wait for word back if we finished or not | |
select { | |
case <-time.After(30*time.Second): | |
// timeout after 30 seconds waiting for app to finish | |
returnCode<-1 | |
case <-done: | |
// if we got a message on done, we finished, so end app | |
returnCode<-0 | |
} | |
}() | |
fmt.Println("waiting for finish") | |
// wait for finishUP channel write to close the app down | |
<-finishUP | |
fmt.Println("stopping things, might take 2 seconds") | |
time.Sleep(2*time.Second) | |
// write to the done channel to signal we are done. | |
done <-struct{}{} | |
os.Exit(<-returnCode) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment