Skip to content

Instantly share code, notes, and snippets.

@uudashr
Last active April 20, 2025 00:33
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")
}
@uudashr
Copy link
Author

uudashr commented Apr 20, 2025

To utilize context, we can use this https://pkg.go.dev/os/signal#NotifyContext

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment