While handling a task, “the user will enter the Ctrl+C command in the command line, and the application will gracefully shut down”, I was looking for best practices. I came to know about signals. A signal is an event generated by UNIX and Linux systems that is sent to a program to notify it about the occurrence.
There are lots of signals. As the task was related to shutdown, I looked at shutdown signals:
- SIGTERM gets sent as the generic software termination signal for almost all shutdown events.
- SIGKILL is sent as a termination signal to quit immediately.
- SIGINT is sent when the user inputs an interrupt signal, such as
Ctrl+C, for user events. - SIGQUIT is sent when the user inputs a quit signal, such as
Ctrl+D, for user events such as force quitting.
So, SIGINT and SIGTERM cover the need for handling shutdown events as well as user inputs.
Diving into code
In Go’s standard library, the os/signal package handles incoming operating system signals, primarily for Unix-like systems. Our code will need to listen for a shutdown signal (SIGINT or SIGTERM), so the usage of channels is a perfect fit for this because of their blocking behavior.
We can create a channel of type os.signal and can use the notify function of the package to access incoming signals, and if SIGINT or SIGTERM exists, the code will send them via channel.
We can write the code as below:
| |
That’s it.