Skip to content

Instantly share code, notes, and snippets.

@husobee
Last active May 18, 2016 20:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save husobee/531062f48f7f35688e7e4c63139a9616 to your computer and use it in GitHub Desktop.
Save husobee/531062f48f7f35688e7e4c63139a9616 to your computer and use it in GitHub Desktop.
handle signals golang
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