Module 2 · Lesson 31 of 131

SIGCHLD and queued signals

Reap child processes with a draining SIGCHLD handler, give status collection one owner, and use queued realtime signals and fault details.

  • Beginner to advanced
  • 8 min read
  • 28 min lab
What you will need

Linux on Ubuntu 24.04 (WSL2 or VM) or an ARM board; GCC, man pages, strace, and GDB

Your place in the module
By the end you can 3 objectives
  • Diagnose EINTR and implement correct SIGCHLD reaping in mysh v2.
  • Evaluate realtime signals, alternate stacks, and signalfd for embedded services.
  • Inspect siginfo_t fields to decode signal origin and faulting addresses
Video coming soonSIGCHLD and queued signals
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Handler safety, blocking and EINTR
  • Handlers must use async-signal-safe operations and preserve errno when needed.
  • Block before testing shared state; sigsuspend atomically unmasks and waits.
  • Standard signals coalesce into one pending indication instead of forming a queue
01

Reap children and keep mysh alive

5 min read

Handlers can now set flags safely, but mysh still needs to collect finished children and carry richer notifications. This lesson answers how mysh reaps children with SIGCHLD and what queued signals carry.

In mysh v1, waitpid(child, ...) collected a foreground child's status. Background children create a new problem: the shell can be waiting at its prompt when they finish. Without collection, an exited child remains a zombie, retaining its wait status and a process-table entry.

With normal zombie retention, a child exit leaves a zombie until waitpid collects its status. Delivery of SIGCHLD alone does not reap the child; mysh must drain waitpid to collect every available status.

  • states: [{"id": "running", "label": "Child running"}, {"id": "zombie", "label": "Child exited; wait status retained"}, {"id": "reaped", "label": "Child status collected; zombie removed"}]
  • transitions: [{"from": "running", "to": "zombie", "event": "Child exits; normal zombie retention"}, {"from": "zombie", "to": "zombie", "event": "SIGCHLD delivered; no wait performed"}, {"from": "zombie", "to": "reaped", "event": "waitpid collects this child status"}]

SIGCHLD can report exit, stop, and continuation. Use SA_NOCLDSTOP when this version only needs exit notifications. This suppresses notifications about stops and continuations; it does not stop children from entering those states.

1Drain completed children inside the handler

The following handler fragment deliberately discards statuses. Use it for a first reaping experiment, before introducing a job table. It calls only an async-signal-safe wait function and preserves errno.

c
#include <errno.h>
#include <signal.h>
#include <sys/wait.h>

static void collect_children(int signo)
{
    int saved_errno = errno;
    (void)signo;
    for (;;) {
        pid_t finished = waitpid(-1, NULL, WNOHANG);
        if (finished > 0)
            continue;
        if (finished == -1 && errno == EINTR)
            continue;
        break;
    }
    errno = saved_errno;
}

static int install_child_handler(void)
{
    struct sigaction action = {0};
    action.sa_handler = collect_children;
    action.sa_flags = SA_NOCLDSTOP | SA_RESTART;
    if (sigemptyset(&action.sa_mask) == -1)
        return -1;
    return sigaction(SIGCHLD, &action, NULL);
}

waitpid(-1, ..., WNOHANG) examines any child without waiting for a running one to finish. A positive result means one status was collected. Zero means children exist but none currently has a requested status. Minus one with ECHILD means there are no matching children left.

Install the action before creating children. Loop because several exits may have coalesced into one SIGCHLD. The next wait after a successful reap can collect another child's status without another notification.

2Give foreground status one owner

Do not simply add that handler beside mysh v1's blocking waitpid(child, ...). Either can collect the foreground child's status first. The loser sees ECHILD, even though the command really existed.

One limited teaching design blocks SIGCHLD before fork() and leaves it blocked while normal code waits for that foreground child. The handler cannot compete during that wait. The parent then restores its old mask, allowing the handler to drain background exits.

This design delays background reaping while the foreground command runs. It also needs an explicit policy for stopped children: a plain exit-only wait can remain blocked after Ctrl-Z. Full stop/resume behavior belongs to the upcoming job-control lesson.

A stronger design gives one normal-code event loop ownership of all waits and all job-table updates. A notification handler only wakes that loop, or signalfd supplies the notification. The loop stores each PID and decoded status, then decides whether to show a prompt.

Step by stepOrder the parent and child setup
  1. Prepare: Install parent dispositions and block SIGCHLD before fork and job registration.

  2. Fork: Create the child while notification delivery cannot race with registration.

  3. Reset child: Restore SIGINT and other shell-specific dispositions to defaults in the child.

  4. Restore child mask: Remove inherited blocking that the new program should not keep, then exec.

  5. Register parent: Record the PID before restoring the parent's previous mask.

  6. Collect: Let the chosen wait owner drain statuses and update foreground completion.

Parent and child run independently after fork; neither setup path is guaranteed to finish first.

3Separate shell and child Ctrl-C policy

For the initial foreground-only v2 exercise, parent and child can remain in the terminal foreground group. Set the parent's SIGINT disposition to SIG_IGN, and reset the child's to SIG_DFL before exec. Ctrl-C then reaches both; the parent survives and the ordinary child terminates.

Ignored dispositions and the mask survive exec; caught handlers become default. Resetting the child is essential. A brief setup window remains before that reset. Robust interactive shells coordinate child setup with terminal foreground ownership.

This shared-group experiment does not isolate background commands from terminal signals. Proper interactive job control gives each job a group and transfers terminal foreground ownership with tcsetpgrp().

Going deeperSIGCHLD ignore is a special case

The default disposition of SIGCHLD is described as ignore, yet Linux normally retains zombie statuses for waiting. Explicitly installing SIG_IGN, or using SA_NOCLDWAIT, changes this and prevents normal zombie retention. A shell that needs exit results must not use those settings as a shortcut for reaping.

After collecting a status, test WIFEXITED before WEXITSTATUS, or WIFSIGNALED before WTERMSIG. If you request stopped and continued statuses, use their corresponding tests too. The SIGCHLD notification itself is not the child's exit code.

One wait ownerChildrenexitSIGCHLDpendingOccurrencescancoalesceChosen waitownerDrainwaitpidCollect allavailableexitstatusesUpdateshell stateChildrenexitSIGCHLDpendingOccurrencescancoalesceChosen waitownerDrainwaitpidCollect allavailableexitstatusesUpdateshell state
A child notification triggers status collection, and one owner updates job state.
02

Use queued signals and inspect fault details

4 min read

An application may need to distinguish several notifications while delivery is blocked. POSIX realtime signals provide that queueing. Select a value from SIGRTMIN through SIGRTMAX, and check that an offset fits at runtime. C libraries reserve signals internally, so never hard-code the numeric range.

Instances of the same realtime signal are delivered in send order. Among different pending realtime signals, Linux prioritizes the lower signal number. This does not create one global send order across different numbers or guarantee a response deadline. Realtime here describes the signal facility, not bounded scheduling latency.

sigqueue() supplies a union sigval, containing either an integer or a pointer-shaped value. This fragment sends an integer to a known target PID. Check for failure.

c
union sigval payload = { .sival_int = 7 };
int event_signal = SIGRTMIN;
if (sigqueue(target_pid, event_signal, payload) == -1)
    perror("sigqueue");  /* Normal sender code, not a handler. */

The receiver reads si_value.sival_int when si_code identifies a queued send. A pointer value is not automatically valid in another process's address space. Use an integer identifier for independently allocated objects, or a separately designed shared-memory scheme.

Queues have limits. Linux accounts queued signals through RLIMIT_SIGPENDING, associated with a real user ID. sigqueue() can fail with EAGAIN when resources are exhausted. A robust protocol needs a retry, backpressure, or explicit loss policy. For bulk data, use a pipe, socket, or message queue instead.

1Decode only fields valid for the origin

With SA_SIGINFO, install void handler(int, siginfo_t *, void *) in sa_sigaction. The second argument describes the event. si_code identifies its origin or cause; examples include SI_USER, SI_QUEUE, SEGV_MAPERR, and SEGV_ACCERR.

For user-sent signals, si_pid and si_uid identify the sender process and real user ID. For a hardware-generated SIGSEGV, si_addr identifies the faulting memory address. For SIGCHLD, si_pid identifies the child and other fields describe its state change. These fields have signal-specific meanings; do not read every field as though every event populated it.

raise(SIGSEGV) creates a software-sent signal. It does not reproduce an invalid-memory fault and does not provide a useful faulting memory address. To test fault addresses, use a disposable test process that deliberately accesses a protected mapping; keep fault testing outside the shell process itself.

2Keep crash reporting independent of printf

To print si_addr in a handler, convert it into hexadecimal using local integer operations and a fixed buffer. Then use write() and terminate with _exit(). Do not use snprintf() for this conversion: it is not guaranteed async-signal-safe.

The following handler fragment targets Linux systems with uintptr_t, an unsigned integer type capable of representing a pointer. It accepts the two common memory-fault codes; other SIGSEGV causes need separate interpretation.

c
#include <stdint.h>
#include <stddef.h>
#include <signal.h>
#include <unistd.h>

static void report_fault(int signo, siginfo_t *info, void *context)
{
    (void)signo;
    (void)context;
    if (info->si_code == SEGV_MAPERR || info->si_code == SEGV_ACCERR) {
        static const char prefix[] = "fault address: 0x";
        static const char hex[] = "0123456789abcdef";
        char line[sizeof prefix + 2 * sizeof(uintptr_t) + 1];
        uintptr_t address = (uintptr_t)info->si_addr;
        size_t used = 0;
        for (size_t i = 0; i < sizeof prefix - 1; ++i)
            line[used++] = prefix[i];
        for (size_t i = 2 * sizeof address; i > 0; --i)
            line[used++] = hex[(address >> ((i - 1) * 4)) & 15u];
        line[used++] = '\n';
        (void)write(STDERR_FILENO, line, used);
    }
    _exit(1);
}

This is a best-effort diagnostic, not a core-dump handler. _exit(1) produces a normal exit status rather than preserving default SIGSEGV core behavior. A crash collector is often better for production diagnostics. Returning from a handler without repairing an actual memory fault can repeat the fault; continuing after memory corruption is unsafe.

Going deeperReserve an alternate stack before a crash

sigaltstack() registers a separate stack region for the calling thread. For its glibc declarations, define _XOPEN_SOURCE 700 before headers. Allocate its memory during normal startup, fill stack_t.ss_sp, ss_size, and ss_flags = 0, and check the registration result. Install the fault action using SA_SIGINFO | SA_ONSTACK and sa_sigaction = report_fault.

Keep the memory alive while registered. Provide adequate space for the target's signal frame and handler, including architecture extensions; MINSIGSTKSZ is a minimum, not a universal production size. A protected guard page can expose overruns, but Linux does not automatically grow your alternate stack.

Each thread needing this protection must register its own alternate stack. If the regular stack is exhausted, the alternate region can let a minimal diagnostic run. It cannot repair corruption or make unsafe reporting functions safe. Nested handlers also need stack space, so keep the crash path short.

Pending bit or queueStandardsignalsRealtimesignalsRepeatedoccurrenceCoalesceswhile pendingSeparatequeuedinstancesSame numberNo occurrencecountSend orderretainedDifferentnumbersOrderunspecifiedLower numberfirstPayloadNot areliablequeuesigval viasigqueueCapacityOne pendingindicationFinite queueresources
Standard pending state coalesces occurrences while realtime signals retain separate queued values.

Key takeaways

  • Standard signals coalesce; one notification can represent several child exits.
  • Give child status collection one owner, and reset inherited child signal policy.
  • Realtime signals carry queued values but have finite queue capacity.
  • siginfo_t fields are signal-specific, and raise(SIGSEGV) does not reproduce a hardware fault address
Reflect
  1. Explain to a colleague, in two sentences: diagnose EINTR and implement correct SIGCHLD reaping in mysh v2.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close