Programming with signals

Sending a signal with kill or alarm, receiving it with sigaction and a handler, the mask and pending signals, pause, SIGCHLD to reap children and the functions allowed in a handler.

  • 30 cards
  • 4 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios

A few cards from the deck

  • Signal: what is it?

    Show the answer

    An asynchronous notification sent by the kernel or by another process, which interrupts the recipient's normal flow.

    Ctrl+C sends SIGINT, kill pid sends SIGTERM, an invalid memory access raises SIGSEGV. A signal carries no data: only its number.

  • What does this program print, whose handler h writes an “A”?

    ```c
    signal(SIGUSR1, h);
    sigset_t m;
    sigemptyset(&m);
    sigaddset(&m, SIGUSR1);
    sigprocmask(SIG_BLOCK, &m, NULL);
    kill(getpid(), SIGUSR1);
    kill(getpid(), SIGUSR1);
    kill(getpid(), SIGUSR1);
    sigprocmask(SIG_UNBLOCK, &m, NULL);
    write(1, "fin\n", 4);
    `

    • Afin
    • AAAfin
    • fin
    • finA
    Show the answer

    Afin

    The three signals merge into a single pending signal. It is delivered at unblocking, before sigprocmask returns: the “A” therefore comes before “fin”. Program run: the output is indeed Afin.

  • A blocked signal stays …; if the same signal arrives three times during the blocking, the handler runs only … at unblocking.

    Show the answer

    A blocked signal stays pending; if the same signal arrives three times during the blocking, the handler runs only once at unblocking.

    A standard signal is represented by a single “pending” bit: multiple arrivals melt into one.

  • Signal handler: what is it?

    Show the answer

    A function of the program that the system calls when a given signal arrives, before resuming the code that was interrupted.

    It can run between any two instructions of the program. It must therefore stay short and touch only safe things, such as a volatile sig_atomic_t variable.

  • A server creates a child per client. Its SIGCHLD handler calls wait(NULL) once. When five clients leave together, ps shows <defunct> processes. What is the cause?

    • wait only reaps children that left through exit, not those killed by a signal
    • Several SIGCHLD merged into one: only one child was reaped
    • The children did not call exit before terminating
    • wait does not work in a handler: kill the zombies instead
    Show the answer

    Several SIGCHLD merged into one: only one child was reaped

    Pending signals are not counted: it is enough for children to finish while the handler runs. Loop on waitpid(-1, NULL, WNOHANG) until it returns 0 or -1. A zombie is already dead: kill changes nothing.