Skip to content

Instantly share code, notes, and snippets.

@arouene
Last active January 18, 2021 17:39
Show Gist options
  • Save arouene/169de81a7eb186405989f5d581bcaf21 to your computer and use it in GitHub Desktop.
Save arouene/169de81a7eb186405989f5d581bcaf21 to your computer and use it in GitHub Desktop.
Signal interruption pattern for Go
func main() {
running := true
// Make a channel the signal handler will subscribe
sigc := make(chan os.Signal, 1)
// Notify will send a sigint or sigterm signal to the
// the previously created channel `sigc`
signal.Notify(sigc, syscall.SIGINT, syscall.SIGTERM)
go func() {
for running {
// Wait for a signal
sig := <-sigc
switch sig {
case syscall.SIGINT:
case syscall.SIGTERM:
running = false
}
}
}()
processing(&running)
fmt.Println("Interrupted.")
}
func processing(running *bool) {
for *running {
// do things...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment