RC: W1 D2 — Unix termination signals
February 13, 2024Today, I paired with Ludwig to implement Conway’s game of life. We had a working version in less than one hour, so that was pretty cool!!
While I was sharing my screen, he told me about the difference between Ctrl-C
, Ctrl-D
and exit
when
interrupting a running process.
I had never given much thought before as to which was the correct one to use, so that was great to have him explain!
That made me wonder about how these really work, so I started digging about it.
In this post, I will share what I learned on this topic.
A process is an instance of a computer program that is being executed. To communicate with one another, processes use “inter-process communication (IPC)”. “Signals” are one of the mechanisms of IPC. When a process receives a signal, its flow of execution is interrupted and a signal handler is executed.
Each of the signals will lead to executing a default action. Some of the common signals and their default actions are:
- SIGINT (“Signal Interrupt”, sent when pressing
Ctrl-C
): it leads to interrupting and terminating the process. - SIGSTP (“Signal Stop”, sent when pressing
Ctrl-Z
): it leads to suspending the current foreground process. It can later be resumed usingfg
orbg
(to resume it in the foreground or background respectively) - SIGKILL (“Signal Kill”, sent when executing
kill -9 ⟨PID⟩
): it leads to terminating immediately the process.
However, some programs override the default action for these signals, by defining their own signal handlers.
For example, bash
has overriden the default action of the SIGINT signal: when you press Ctrl-C
, instead of quitting,
it prints a new prompt line!
There are other commands we can press that don’t send any signal. For example, Ctrl-D
sends an EOF (End Of File)
marker. For a program that expects standard input, this indicates the end of the input.
Funnily, if this is pressed at a shell prompt, it will be interpreted as a sign that there is no more input.
Thus, it results in exiting the shell.
As for exit
, it is a shell built-in command that also results in exiting it.