...

/

Handling OS Signals

Handling OS Signals

Learn to handle OS signals in CLI applications using the Context package.

When writing CLI applications, there are occasions when a developer wants to handle OS signals. The most common example is a user trying to exit a program, usually through a keyboard shortcut.

In these cases, we may want to do some file cleanup before exiting or cancel a call we made to a remote system.

In this lesson, we’ll talk about how we can capture and respond to these events to make our applications more robust.

Capturing an OS signal

Go deals with two types of OS signals:

  • Synchronous

  • Asynchronous

Synchronous signals generally revolve around program errors. Go treats these as runtime panics, and therefore, interception of these can be handled with a defer statement. There are different asynchronous signals, depending on the platform, but for a Go programmer, the most relevant are as follows:

  • SIGHUP: The connected terminal disconnected.

  • SIGTERM: Please quit and do cleanup (generated from a program).

  • SIGINT: The same as SIGTERM (sent from the terminal).

  • SIGQUIT: The same as SIGTERM plus a core dump (sent from the terminal).

  • SIGKILL: The program must quit; this signal cannot be captured.

In situations where these arise, it can be useful to intercept these signals so that we can cancel ongoing operations and do a cleanup before exiting. It should be noted that SIGKILL cannot be intercepted, and SIGHUP is simply an indication that a process has lost its terminal, ...