Last active
January 18, 2021 17:39
-
-
Save arouene/169de81a7eb186405989f5d581bcaf21 to your computer and use it in GitHub Desktop.
Signal interruption pattern for Go
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
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