Created
April 15, 2015 16:29
-
-
Save trevrosen/049a6880c3f53b71b8cd to your computer and use it in GitHub Desktop.
Example of using goroutines and channels to cleanly handle SIGINT
This file contains hidden or 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" | |
"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