Last active
October 2, 2023 21:09
-
-
Save uudashr/3cf820e3ba902d3c6387abc82c815e66 to your computer and use it in GitHub Desktop.
Listening for signal termination in Golang (AKA shutdown hook)
This file contains 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" | |
"syscall" | |
) | |
// Program that will listen to the SIGINT and SIGTERM | |
// SIGINT will listen to CTRL-C. | |
// SIGTERM will be caught if kill command executed. | |
// | |
// See: | |
// - https://en.wikipedia.org/wiki/Unix_signal | |
// - https://www.quora.com/What-is-the-difference-between-the-SIGINT-and-SIGTERM-signals-in-Linux | |
// - http://programmergamer.blogspot.co.id/2013/05/clarification-on-sigint-sigterm-sigkill.html | |
func main() { | |
done := make(chan struct{}) | |
go func() { | |
log.Println("Listening signals...") | |
c := make(chan os.Signal, 1) // we need to reserve to buffer size 1, so the notifier are not blocked | |
signal.Notify(c, os.Interrupt, syscall.SIGTERM) | |
<-c | |
close(done) | |
}() | |
<-done | |
log.Println("Done") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think that would be use of
context.Context