Skip to content

Instantly share code, notes, and snippets.

@uudashr
Last active October 2, 2023 21:09
Show Gist options
  • Save uudashr/3cf820e3ba902d3c6387abc82c815e66 to your computer and use it in GitHub Desktop.
Save uudashr/3cf820e3ba902d3c6387abc82c815e66 to your computer and use it in GitHub Desktop.
Listening for signal termination in Golang (AKA shutdown hook)
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")
}
@morningsend
Copy link

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?

@uudashr
Copy link
Author

uudashr commented Jan 8, 2020

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.

@isereb
Copy link

isereb commented Jul 6, 2021

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?

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