Signals
The provided Go code demonstrates how to handle signals such as SIGINT
and SIGTERM
in a Go program using channels and goroutines. Here's a breakdown of the code:
Explanation:
sigs := make(chan os.Signal, 1)
: Creates a buffered channel (sigs
) to receive signals. The buffer size is set to 1 to avoid missing signals if multiple signals arrive quickly.signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
: Notifies the program to listen forSIGINT
(Ctrl+C) andSIGTERM
(termination request) signals. When a signal is received, it will be sent to thesigs
channel.done := make(chan bool, 1)
: Creates a buffered channel (done
) to signal when the program is done.go func() { ... }()
: Starts a goroutine to handle signals. Inside the goroutine, it waits for a signal on thesigs
channel, prints the received signal, and signals that the program is done by sending a value to thedone
channel.fmt.Println("awaiting signal")
: Prints a message indicating that the program is waiting for a signal.<-done
: Waits for the program to be done (signal received) by receiving a value from thedone
channel.fmt.Println("exiting")
: Prints a message indicating that the program is exiting.
This code allows the program to gracefully handle termination signals and perform necessary cleanup before exiting.
Last updated
Was this helpful?