Sending signals to other processes

After seeing the way in which incoming signals are handled, let's take a look at how to send signals to other processes programmatically. The os.Process structure is the only tool we need—its Signal method makes it possible to send a signal to the project. It's that easy!

The less simple part is obtaining the process. There are two use cases, as follows:

The first use case is simpler, as we already have the process as a variable, or as an attribute of an exec.Cmd variable, and we can call the method directly.

The other use case requires searching for the process by PID using the os.FindProcess method, as follows:

p, err := os.FindProcess(pid)
if err != nil {
panic(err)
}

Once we have os.Process, we can use its Signal method to send a specific signal to it, as follows:

if err = p.Signal(syscall.SIGTERM); err != nil {
panic(err)
}

The type of signal we will send to a process depends on the destination process and the behavior we want to suggest, such as an interruption or a termination.