Handling Unix signals

Go provides the os/signal package to programmers to help them work with signals. This section will show you how to use it for Unix signal handling.

First let's present some useful information about Unix signals. Have you ever pressed Ctrl + C in order to stop a running program? If your answer is Yes, then you are already familiar with signals because Ctrl + C sends the SIGINT signal to a program. Strictly speaking, Unix Signals are software interrupts that can be accessed either by name or by number, and they offer a way to handle asynchronous events on a Unix system. There are two ways to send a signal: by name or by number. Generally speaking, it is safer to send a signal by name because you are is less likely to send the wrong signal accidentally.

A program cannot handle all of the available signals: some signals cannot be caught, nor can they be ignored. The SIGKILL and SIGSTOP signals cannot be caught, blocked, or ignored. The reason for this is that they provide the kernel and the root user a way of stopping any process they want. The SIGKILL signal, which is also known by the number 9, is usually called in extreme conditions where you need to act fast. Thus, it is the only signal that is usually called by number, simply because it is quicker to do so.

signal.SIGINFO is not available on Linux machines, which means that if you find it in a Go program that you want to run on a Linux machine, you need to replace it with another signal, or your Go program will not be able to compile and execute.

The most common way to send a signal to a process is by using the kill(1) utility. By default, kill(1) sends the SIGTERM signal. If you want to find all of the supported signals on your Unix machine, you should execute the kill -l command.

If you try to send a signal to a process without having the required permissions, kill(1) will not do the job and you will get an error message similar to the following:

$ kill 1210
-bash: kill: (1210) - Operation not permitted
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.66.156