Handling Signals

Learn how to handle signals by using the os/signal package.

Overview

The last feature we’ll add to goci is the ability to handle operating system signals. Signals are commonly used on Unix/Linux operating systems to communicate events among running processes. Typically, signals are used to terminate programs that aren’t responding or are running for a long time. For example, pressing “Ctrl+C” on the keyboard sends the interrupt signal (SIGINT) to a running program, which interrupts its execution.

In Go, we handle signals by using the os/signal package. For more information, consult its documentation.

By default, when a program receives an interrupt signal, it stops executing immediately. This can lead to data loss and other consequences. It’s important to handle signals appropriately so the program has a chance to clean up used resources, save data, and exit cleanly. This is even more relevant for an automation tool such as goci because it can receive a signal from other parts of the automation process.

Updating the error.go file

For goci specifically, no cleanup is needed. When handling signals, the tool will exit cleanly but provide an appropriate error status and message, which makes downstream applications aware that goci didn’t finish properly, allowing them to decide which actions to take. Since this error occurs outside a CI step, handle it using another error value instead of your custom error type that was designed to handle step errors. Edit the file errors.go and add another error value ErrSignal, representing an error when receiving a signal:

Get hands-on with 1200+ tech skills courses.