Skip to content

Instantly share code, notes, and snippets.

@trevrosen
Created April 15, 2015 16:29
Show Gist options
  • Save trevrosen/049a6880c3f53b71b8cd to your computer and use it in GitHub Desktop.
Save trevrosen/049a6880c3f53b71b8cd to your computer and use it in GitHub Desktop.
Example of using goroutines and channels to cleanly handle SIGINT
package main
import (
"fmt"
"log"
"os"
"os/signal"
"time"
)
// create a single-member channel to hold signals from the OS
var osSignalChan = make(chan os.Signal, 1)
func main() {
signal.Notify(osSignalChan, os.Interrupt)
// run caughtInterrupt with a goroutine
go caughtInterrupt()
// loop forever
for {
fmt.Println("Doing some stuff...")
time.Sleep(1000 * time.Millisecond)
}
}
// reading from osSignalChan will block until there is something there to read,
// so the goroutine calling this function will block on the first line
func caughtInterrupt() {
<-osSignalChan
log.Println("Caught interrupt")
log.Println("No longer doing stuff")
os.Exit(0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment