How does Ctrl-C terminate a child process?

BashShellProcessSh

Bash Problem Overview


I am trying to understand how CTRL+C terminates a child but not a parent process. I see this behavior in some script shells like bash where you can start some long-running process and then terminate it by entering CTRL-C and the control returns to the shell.

Could you explain how does it work and in particular why isn't the parent (shell) process terminated?

Does the shell have to do some special handling of CTRL+C event and if yes what exactly does it do?

Bash Solutions


Solution 1 - Bash

Signals by default are handled by the kernel. Old Unix systems had 15 signals; now they have more. You can check </usr/include/signal.h> (or kill -l). CTRL+C is the signal with name SIGINT.

The default action for handling each signal is defined in the kernel too, and usually it terminates the process that received the signal.

All signals (but SIGKILL) can be handled by program.

And this is what the shell does:

  • When the shell running in interactive mode, it has a special signal handling for this mode.
  • When you run a program, for example find, the shell:
  • forks itself
  • and for the child set the default signal handling
  • replace the child with the given command (e.g. with find)
  • when you press CTRL+C, parent shell handle this signal but the child will receive it - with the default action - terminate. (the child can implement signal handling too)

You can trap signals in your shell script too...

And you can set signal handling for your interactive shell too, try enter this at the top of you ~/.profile. (Ensure than you're a already logged in and test it with another terminal - you can lock out yourself)

trap 'echo "Dont do this"' 2

Now, every time you press CTRL+C in your shell, it will print a message. Don't forget to remove the line!

If interested, you can check the plain old /bin/sh signal handling in the source code here.

At the above there were some misinformations in the comments (now deleted), so if someone interested here is a very nice link - how the signal handling works.

Solution 2 - Bash

First, read [the Wikipedia article on the POSIX terminal interface][1] all of the way through.

The SIGINT signal is generated by the terminal line discipline, and broadcast to all processes in the terminal's foreground process group. Your shell has already created a new process group for the command (or command pipeline) that you ran, and told the terminal that that process group is its (the terminal's) foreground process group. Every concurrent command pipeline has its own process group, and the foreground command pipeline is the one with the process group that the shell has programmed into the terminal as the terminal's foreground process group. Switching "jobs" between foreground and background is (some details aside) a matter of the shell telling the terminal which process group is now the foreground one.

The shell process itself is in yet another process group all of its own and so doesn't receive the signal when one of those process groups is in the foreground. It's that simple.

[1]: http://en.wikipedia.org/wiki/POSIX_terminal_interface "POSIX terminal interface"

Solution 3 - Bash

The terminal sends the INT (interrupt) signal to the process that is currently attached to the terminal. The program then receives it, and could choose to ignore it, or quit.

No process is necessarily being forcibly closed (although by default, if you don't handle sigint, I believe the behaviour is to call abort(), but I'd need to look that up).

Of course, the running process is isolated from the shell that launched it.

If you wanted the parent shell to go, launch your program with exec:

exec ./myprogram

That way, the parent shell is replaced by the child process

Solution 4 - Bash

setpgid POSIX C process group minimal example

It might be easier to understand with a minimal runnable example of the underlying API.

This illustrates how the signal does get sent to the child, if the child didn't change its process group with setpgid.

main.c

#define _XOPEN_SOURCE 700
#include <assert.h>
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

volatile sig_atomic_t is_child = 0;

void signal_handler(int sig) {
    char parent_str[] = "sigint parent\n";
    char child_str[] = "sigint child\n";
    signal(sig, signal_handler);
    if (sig == SIGINT) {
        if (is_child) {
            write(STDOUT_FILENO, child_str, sizeof(child_str) - 1);
        } else {
            write(STDOUT_FILENO, parent_str, sizeof(parent_str) - 1);
        }
    }
}

int main(int argc, char **argv) {
    pid_t pid, pgid;

    (void)argv;
    signal(SIGINT, signal_handler);
    signal(SIGUSR1, signal_handler);
    pid = fork();
    assert(pid != -1);
    if (pid == 0) {
        is_child = 1;
        if (argc > 1) {
            /* Change the pgid.
             * The new one is guaranteed to be different than the previous, which was equal to the parent's,
             * because `man setpgid` says:
             * > the child has its own unique process ID, and this PID does not match
             * > the ID of any existing process group (setpgid(2)) or session.
             */
            setpgid(0, 0);
        }
        printf("child pid, pgid = %ju, %ju\n", (uintmax_t)getpid(), (uintmax_t)getpgid(0));
        assert(kill(getppid(), SIGUSR1) == 0);
        while (1);
        exit(EXIT_SUCCESS);
    }
    /* Wait until the child sends a SIGUSR1. */
    pause();
    pgid = getpgid(0);
    printf("parent pid, pgid = %ju, %ju\n", (uintmax_t)getpid(), (uintmax_t)pgid);
    /* man kill explains that negative first argument means to send a signal to a process group. */
    kill(-pgid, SIGINT);
    while (1);
}

GitHub upstream.

Compile with:

gcc -ggdb3 -O0 -std=c99 -Wall -Wextra -Wpedantic -o setpgid setpgid.c

Run without setpgid

Without any CLI arguments, setpgid is not done:

./setpgid

Possible outcome:

child pid, pgid = 28250, 28249
parent pid, pgid = 28249, 28249
sigint parent
sigint child

and the program hangs.

As we can see, the pgid of both processes is the same, as it gets inherited across fork.

Then whenever you hit Ctrl+C it outputs again:

sigint parent
sigint child
                                                                                         

This shows how:

  • to send a signal to an entire process group with kill(-pgid, SIGINT)
  • Ctrl+C on the terminal sends a kill to the entire process group by default

Quit the program by sending a different signal to both processes, e.g. SIGQUIT with Ctrl+</kbd>.

Run with setpgid

If you run with an argument, e.g.:

./setpgid 1
                                                                                         

then the child changes its pgid, and now only a single sigint gets printed every time from the parent only:

child pid, pgid = 16470, 16470
parent pid, pgid = 16469, 16469
sigint parent

And now, whenever you hit Ctrl+C only the parent receives the signal as well:

sigint parent

You can still kill the parent as before with a SIGQUIT (Ctrl+</kbd>) however the child now has a different PGID, and does not receive that signal! This can seen from:

ps aux | grep setpgid

You will have to kill it explicitly with:

kill -9 16470
                                                                                         

This makes it clear why signal groups exist: otherwise we would get a bunch of processes left over to be cleaned manually all the time.

Tested on Ubuntu 18.04.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvitautView Question on Stackoverflow
Solution 1 - Bashjm666View Answer on Stackoverflow
Solution 2 - BashJdeBPView Answer on Stackoverflow
Solution 3 - BashseheView Answer on Stackoverflow
Solution 4 - BashCiro Santilli Путлер Капут 六四事View Answer on Stackoverflow