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") | |
} |
Need more detail on what you want to do here. But I suggest to use https://github.com/oklog/run
Those signals are from OS. One goroutine to listen is enough.
Hi, I have a question. What is the best way to signal shutdown by other goroutines?
Also if multiple goroutines signal shutdown at the same time, would some of them they be blocked since the channelc
only has capacity of 1?
I think that would be use of context.Context
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, I have a question. What is the best way to signal shutdown by other goroutines?
Also if multiple goroutines signal shutdown at the same time, would some of them they be blocked since the channel
c
only has capacity of 1?