Introduction
The Signals challenge demonstrates how to handle Unix signals in Go programs using channels.
This tutorial is from open-source community. Access the source code
The Signals challenge demonstrates how to handle Unix signals in Go programs using channels.
In some cases, we want our Go programs to handle Unix signals intelligently. For instance, we might want a server to shut down gracefully when it receives a SIGTERM
, or a command-line tool to stop processing input if it receives a SIGINT
.
os.Signal
notifications.signal.Notify
.## When we run this program it will block waiting for a
## signal. By typing `ctrl-C` (which the
## terminal shows as `^C`) we can send a `SIGINT` signal,
## causing the program to print `interrupt` and then exit.
$ go run signals.go
awaiting signal
^C
interrupt
exiting
The Signals challenge demonstrates how to handle Unix signals in Go programs using channels. By creating a buffered channel to receive os.Signal
notifications and registering the channel to receive notifications of specified signals using signal.Notify
, we can gracefully handle signals and exit the program when the expected signal is received.