## Introduction to interrupts and signals

An interrupt is an event that alters the normal execution flow of a program and can be generated by hardware devices or even by the CPU itself. When an interrupt occurs the current flow of execution is suspended and the interrupt handler runs. After the interrupt handler runs the previous execution flow is resumed. There are three types of events that can cause the CPU to interrupt: hardware interrupts, software interrupts, and exceptions.

Signals are nothing but software interrupts that notifies a process that an event has occurred. These events might be requests from users or indications that a system problem (such as a memory access error) has occurred. Every signal has a signal number and a default action defined. A process can react to them in any of the following ways:

- a default (OS-provided) way
- catch the signal and handle them in a program-defined way
- ignore the signal entirely

## Types of signals

To list available signals in a Linux system, you can use the command `kill -l` . 
The table below lists the signals 1 to 20. To get a full list of signals, you can refer [here](https://en.wikipedia.org/wiki/Signal_(IPC)).

| Signal name     | Signal number    | Default Action    | Meaning    |
| :------------- | :----------: | :-----------: | :-----------: |
|  SIGHUP |  1   | Terminate   | Hangup detected on controlling terminal or death of controlling process |
| SIGINT  |  2   | Terminate   | Interrupt from keyboard |
| SIGQUIT  |  3   | Core dump   | Quit from keyboard |
| SIGILL  |  4   | Core dump   | Illegal instruction |
| SIGTRAP  |  5   | Core dump   | Trace/breakpoint trap for debugging |
| SIGABRT , SIGIOT  |  6   | Core dump   | Abnormal termination |
| SIGBUS  |  7   | Core dump   | Bus error |
| SIGFPE  |  8  | Core dump   | Floating point exception |
| SIGKILL  |  9  | Terminate  | Kill signal(cannot be caught or ignored) |
| SIGUSR1  |  10  | Terminate  | User-defined signal 1 |
| SIGSEGV  |  11  | Core dump  | Invalid memory reference |
| SIGUSR2  |  12  | Terminate  | User-defined signal 2 |
| SIGPIPE  |  13  | Terminate  | Broken pipe;write pipe with no readers |
| SIGALRM  |  14  | Terminate  | Timer signal from alarm |
| SIGTERM  |  15  | Terminate  | Process termination |
| SIGSTKFLT | 16 | Terminate  | Stack fault on math co-processor |
| SIGCHLD | 17 | Ignore | Child stopped or terminated |
| SIGCONT | 18 | Continue | Continue if stopped |
| SIGSTOP | 19 | Stop | Stop process (can not be caught or ignore) |
| SIGTSTP | 20 | Stop | Stop types at tty |

## Sending signals to process

There are three different ways to send signals to processes:

- Sending signal to process using kill

Kill command can be used to send signals to process. By default a SIGTERM signal is sent but a different type of signal can be sent to the process by defining the signal number(or signal name).
For example, the command `kill -9 367` sends SIGKILL to the process with PID 367

- Sending signal to process via keyboard 

Signals can be sent to a running process by pressing some specific keys.
For example, holding Ctrl+C sends SIGINT to the process which kills it.

- Sending signal to process via another process 

A process can send a signal to another process via the kill() system call.
`int  kill(pid_t pid, int sig)` system call takes 2 arguments, pid of the process you wish to send the signal to and the signal number of the desired signal.

## Handling signals

Referring to the table of signals in the previous section, you can see that there are default handlers attached to all signals when the program is started. When we invoke signal to attach our own handler, we are over-riding the default behaviour of the program in response to that signal. Specifically, if we attach a handler to SIGINT, the program will no longer terminate when you press <ctrl>+C (or send the program a SIGINT by any other means); rather, the function specified as the handler will be invoked instead which will define the behaviour of the program in response to that signal.

Let’s take an example of handling SIGINT signal and terminating a program. We will use Python’s *signal* library to achieve this. 

When we press Ctrl+C, SIGINT signal is sent. From the signals table, we see that the default action for SIGINT is to terminate the process.
To illustrate how the process reacts to the default action and a signal handler, let us consider the below example. 

Default Action of SIGINT:

Let us first run the below lines in a python environment:

```
while 1:
        continue
```
Now let us press "Ctrl+C". 

On pressing "Ctrl+C" , a SIGINT interrupt is sent to the process and the default action for SIGINT as per the table we saw in the previous section is to terminate the process.  We see that the while loop is terminated and we get the below on our console:

```
^CTraceback (most recent call last):
  File "<stdin>", line 2, in <module>
  KeyboardInterrupt
```

The process terminated(default action) since it received a SIGINT(Keyboard Interrupt) when we pressed Ctrl+C.

Signal Handler for SIGINT:

Let us run the below lines of code in the Python environment. 

```
import signal
import sys

#Start of signal_handler function

def signal_handler(signal, frame):
        print ('You pressed Ctrl+C!')

# End of signal_handler function

signal.signal(signal.SIGINT, signal_handler)

```

This is an example of a program that defines its own signal handler for SIGINT , overriding the default action.

Now let us run the while and continue statement as we did previously. 

```
while 1:
        continue
```

Do we see any changes when Ctrl+C is pressed? Does the program terminate? 
We see the below output:

```
^CYou pressed Ctrl+C!
```
Everytime we press Ctrl+C, we just the see the above message and the program does not terminate. Inorder to terminate the program, you can press Ctrl+Z which sends the SIGSTOP signal whose default action is to stop the process. 

In the case of the signal handler, we define a function *signal_handler()* which prints “You pressed Ctrl+C!” and does not terminate the program. The handler is called with two arguments, the signal number and the current stack frame (None or a [frame object](https://docs.python.org/3/reference/datamodel.html#frame-objects)). *signal.signal()* allows defining custom handlers to be executed when a signal is received. Its two arguments are the signal number(name) you want to trap and the name of the signal handler.

## Role of signals in system calls with the example of *wait()*

The *wait()* system call waits for one of the children of the calling process to terminate
and returns the termination status of that child in the buffer pointed to by *statusPtr*.

- If the parent process calls the *wait()* system call, then the execution of the parent is suspended until the child is terminated.
- At the termination of the child, a SIGCHLD signal is generated which is delivered to the parent by the kernel. SIGCHLD signal indicates to the parent that there is some information on the child that needs to be collected.
- Parent, on receipt of SIGCHLD , reaps the status of the child from the process table. Even though the child is terminated, there is an entry in the process table corresponding to the child where the process entry and PID is stored.
- When the parent collects the status, this entry is deleted. Thus, all the traces of the child process are removed from the system.

If the parent decides not to wait for the child’s termination and it executes its subsequent task, or fails to read the exit status of the child, there remains an entry in the process table even after the termination of the child. This state of the child process is known as the Zombie state. In order to avoid long-lasting zombies, we need to have code that calls *wait()* after the child process is created. It is generally good to create a signal handler for the SIGCHLD signal, calling one of the wait-family functions in a loop, until no uncollected child data remains.

A child process becomes orphaned, if its parent process terminates before the child .The orphaned child is adopted by init/systemd, the ancestor of all processes, whose process ID is 1. Further calls to fetch the parent pid of this process returns 1.
