Module 2 · Lesson 8 of 30

Signals (mysh v2)

Understand Linux signals, write safe handlers, fix child-reaping races in mysh v2, and integrate signals with event loops.

  • Beginner to advanced
  • 31 min read
  • 60 min lab
What you will need

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

By the end you can 6 objectives
  • Describe signal generation, pending state, delivery, and default actions.
  • Choose appropriate signals and send them to a process or process group.
  • Install sigaction handlers that obey async-signal-safety rules.
  • Use masks and sigsuspend to prevent missed wakeups.
  • Diagnose EINTR and implement correct SIGCHLD reaping in mysh v2.
  • Evaluate realtime signals, alternate stacks, and signalfd for embedded services.
Read the lesson below; the video will appear here when published.
01

Why a running program needs an interruption

2 min read

Run sleep 60 in a terminal, then press Ctrl-C. You do not have to wait for the minute to finish. The terminal asks Linux to interrupt the foreground program.

A A thread is one flow of instructions within a process. Your mysh from the previous lesson has one thread, so begin with that simpler case.

Linux can deliver the notification while the program waits or works. A service manager can also request shutdown without knowing its internals.

A program, expired timer, child exit, or processor fault can generate a signal. An invalid memory access is one such fault.

Calling all signals asynchronous would hide an important difference. An asynchronous notification comes from outside the instruction currently running. A synchronous fault results from that instruction itself. An invalid load normally faults the thread that attempted it, rather than an arbitrary thread.

The A handler is a function called when the signal is delivered. A disposition belongs to the process and is shared by its threads.

The lifecycle has separate stages. Generation records that an event occurred. A Delivery applies the selected action. A blocked signal can stay pending until it becomes eligible for delivery.

Step by stepFrom event to action
  1. Generate: A sender, terminal, timer, or fault identifies a signal and its target.

  2. Record: Linux records pending state and any associated signal information.

  3. Select: Linux finds an eligible receiving thread when delivery is possible.

  4. Apply: The disposition causes termination, ignoring, stopping, or entry to a handler.

  5. Resume: A returning handler restores the interrupted context; some interrupted operations restart.

An ignored signal normally does not wait around for a future handler. Blocking and ignoring are different choices. Likewise, a successful send does not prove that the target ran a handler or completed shutdown.

On an ARM gateway, SIGTERM can request shutdown, while faults identify broken code. Your handler runs in user space, separately from kernel hardware-interrupt handling.

Signal lifecycleGenerateSender,terminal,timer, orfaultPendingBlockedsignals canwaitEligibledeliveryApplydispositionDefault,ignore, orhandlerReturn ifhandledRestoresavedexecutionstateGenerateSender,terminal,timer, orfaultPendingBlockedsignals canwaitEligibledeliveryApplydispositionDefault,ignore, orhandlerReturn ifhandledRestoresavedexecutionstate
Generation and pending state come before delivery and the selected action.
02

Choose the action and the recipient

3 min read

Start with names, not numbers. Signal numbers can vary between Linux architectures. The shell command kill -l lists names available on your system; BusyBox can provide a smaller command implementation.

These are standard signals, the traditional set. Termination ends the process. A core action ends it and may produce a memory snapshot for debugging. Ignoring takes no action. Stopping suspends execution until continued, usually with SIGCONT.

Signal Common source or use Default action
SIGINT Terminal Ctrl-C Terminate
SIGTERM Request orderly shutdown Terminate
SIGKILL Force termination Terminate
SIGSTOP Force a stop Stop
SIGHUP Terminal hangup; conventionally reload configuration Terminate
SIGSEGV Invalid memory access Core
SIGCHLD Child exits, stops, or continues Ignore
SIGPIPE Write to a pipe with no readers Terminate
SIGALRM alarm() timer expires Terminate
SIGQUIT Terminal Ctrl-\ Core
SIGTSTP Terminal Ctrl-Z Stop

Core creation depends on limits, policy, storage, and any collector; boards may disable it. If SIGPIPE is ignored, a write with no pipe readers fails with EPIPE instead of terminating.

SIGKILL and SIGSTOP cannot be caught, ignored, or blocked. SIGTERM is catchable, but its default action does no application cleanup. To close a database cleanly, the application must implement that behavior. SIGHUP means reload only when the receiving program defines that convention.

A The terminal sends Ctrl-C, Ctrl-\, and Ctrl-Z to its foreground process group when its signal-generating mode is enabled. These keys do not simply target the child PID known to your shell.

To test sending safely, create your own disposable child and use its recorded PID. The final wait collects its status; in Bash, a signal-terminated child makes wait return a nonzero status.

bash
sleep 60 &
child=$!
kill -TERM "$child"
wait "$child"

In C, kill(pid, SIGTERM) targets a positive process ID. kill(0, SIGTERM) targets the caller's process group. kill(-pgid, SIGTERM) targets group pgid, provided pgid is greater than one. killpg(pgid, SIGTERM) expresses group sending directly. Check return values and permissions rather than assuming every group member received the signal.

raise(SIGUSR1) sends a signal to the calling thread. SIGUSR1 is an application-defined signal whose default action is termination. alarm(5) schedules SIGALRM after five seconds, replacing the process's previous alarm; alarm(0) cancels it. Expiration is not a promise of immediate execution.

Linux checks sender credentials or suitable privilege, with special rules for SIGCONT. A send with signal zero checks existence and permission without delivering a signal. It cannot prevent the target exiting immediately afterward. Reusing a numeric PID later can also address a different process.

Ctrl-C targets a groupTerminalKernelmysh parentForegroundchildCtrl-CSIGINT:ignoredSIGINT: default termination1. Terminal → KernelCtrl-C2. Kernel → mysh parentSIGINT: ignored3. Kernel → Foreground childSIGINT: default termination
One foreground process group receives terminal-generated signals together.
03

Install a precise response with sigaction

2 min read

Suppose SIGTERM should ask a monitoring loop to finish. The handler can set a flag, leaving cleanup to the loop. This avoids running complex cleanup at an arbitrary point inside another library function.

The older signal() interface has historical System V and BSD differences in handler persistence, masking, and restarting. Common glibc configurations wrap BSD-style behavior. Use sigaction() to make these choices explicit across C libraries.

Use sigaction() for new handlers. Its first argument identifies the signal. Its second points to the new settings. Its third optionally receives the old settings. Pass NULL as the second argument to query without changing anything.

The Within struct sigaction, sa_mask adds signals to that mask while the handler runs. The triggering signal is also blocked during its handler unless you request SA_NODEFER.

1Define the smallest useful handler

This fragment records a request only. Include these headers before using the declarations, and put the feature-test macro before every header. The macro asks the C library to expose the required POSIX declarations.

c
#define _POSIX_C_SOURCE 200809L
#include <signal.h>

static volatile sig_atomic_t stop_requested;

static void request_stop(int signo)
{
    (void)signo;
    stop_requested = 1;
}

static int install_stop_handler(void)
{
    struct sigaction action = {0};
    action.sa_handler = request_stop;
    if (sigemptyset(&action.sa_mask) == -1)
        return -1;
    action.sa_flags = 0;
    return sigaction(SIGTERM, &action, NULL);
}

Check install_stop_handler() before entering the service loop. SIG_DFL in sa_handler restores the default action; SIG_IGN explicitly ignores the signal.

2Select flags deliberately

SA_RESTART requests restart for eligible interrupted operations. Leaving it clear can help a blocking loop regain control after a shutdown request. Neither setting eliminates the need to understand each blocking interface.

SA_SIGINFO selects the three-argument handler form through sa_sigaction, covered later. Do not set both handler members: implementations may store them in a union. Applications should leave implementation fields such as sa_restorer alone.

SA_NOCLDSTOP suppresses SIGCHLD notifications for child stops and continuations. SA_NOCLDWAIT changes child termination handling so zombies are not retained. The latter is unsuitable when mysh needs to collect exit statuses.

After handler return, Linux restores the earlier mask. Another pending handler can run before normal code resumes.

A sigaction configurationHandler selectionsa_handler or sa_sigactionTemporary masksa_mask adds blocked signalsBehavior flagssa_flags controls delivery and restartInstall with sigactionHandler selectionsa_handler or sa_sigactionTemporary masksa_mask adds blocked signalsBehavior flagssa_flags controls deliveryand restartInstall with sigaction
The action structure selects a callback, temporary blocking, and delivery flags.
04

Keep handlers safe when they interrupt anything

3 min read

Imagine the main code is changing a buffered output stream. SIGCHLD arrives, and its handler calls printf() on that stream. The library may be interrupted halfway through changing its bookkeeping. The handler can observe inconsistent state or encounter locks already held by interrupted code.

The POSIX list includes write(), _exit(), and waitpid(). It does not include printf(), malloc(), free(), perror(), or ordinary mutex locking.

A mutex is a lock that protects shared state. A thread-safe function may rely on one. If a handler waits for a lock held by interrupted code, neither can progress. This is a deadlock.

For a fixed diagnostic, use an already prepared message and write(). This handler fragment preserves errno, the error indicator used by normal code. Without that preservation, a failing handler operation could overwrite an error the interrupted code still needs to inspect.

c
#include <errno.h>
#include <signal.h>
#include <unistd.h>

static volatile sig_atomic_t notification_seen;

static void note_notification(int signo)
{
    int saved_errno = errno;
    static const char message[] = "notification received\n";
    (void)signo;
    notification_seen = 1;
    (void)write(STDERR_FILENO, message, sizeof message - 1);
    errno = saved_errno;
}

The code treats the message as best effort. A write can fail or transfer fewer bytes. Even a safe function can block: stderr might refer to a full pipe. Production handlers often set only a flag or write to a nonblocking notification pipe.

volatile tells the compiler that the value can change outside the visible normal flow. It does not turn a larger structure into an atomic object.

Assigning a flag is much easier to reason about than incrementing a shared counter. An increment contains a read and a write; it can conflict with another update. Moreover, a counter cannot recover standard signal occurrences that Linux already merged.

Block the relevant signal around a normal-code read-and-clear sequence if clearing must not erase a new notification. Do not use volatile sig_atomic_t as a general thread synchronization tool. Threads and their memory-ordering rules arrive later in M2.

Cleanup belongs in normal code

exit() runs library cleanup and registered callbacks, so it is unsuitable for an arbitrary handler. _exit() terminates without that cleanup. For graceful shutdown, set a flag and let normal code close resources.

Defer complex workInterruptedcodeEnterhandlerAssign flagReturnNormalcleanupLogging andresourcereleaseInterruptedcodeEnterhandlerAssign flagReturnNormalcleanupLogging andresourcerelease
The handler records a request while normal code owns logging and resource cleanup.
05

Block, inspect, and wait without a missed wakeup

4 min read

Suppose you test a flag, find zero, then call pause(). A signal might run between those operations. Your handler sets the flag, returns, and then pause() sleeps awaiting a new signal. The event happened, but your program appears stuck.

Use a sigset_t to describe signals. sigemptyset() starts with none; sigfillset() starts with all. sigaddset() adds one and sigdelset() removes one. sigismember() returns one for membership, zero for absence, and minus one on error.

sigprocmask(SIG_BLOCK, &set, &old) adds blocked signals while saving the previous mask. SIG_UNBLOCK removes selected signals. SIG_SETMASK replaces the whole mask. Save and restore the original rather than assuming it was empty.

1Hold delivery before creating the event

This complete experiment blocks SIGUSR1, raises it twice, inspects pending state, then waits safely for its handler. Save it as pending_demo.c on Linux. It uses SIGUSR1 solely as a controlled notification.

c
#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

static volatile sig_atomic_t ready;

static void mark_ready(int signo)
{
    (void)signo;
    ready = 1;
}

static void fail(const char *operation)
{
    perror(operation);
    exit(EXIT_FAILURE);
}

int main(void)
{
    sigset_t held, old, pending, during_wait;
    struct sigaction action = {0};
    action.sa_handler = mark_ready;
    if (sigemptyset(&action.sa_mask) == -1 ||
        sigemptyset(&held) == -1 ||
        sigaddset(&held, SIGUSR1) == -1)
        fail("signal set");
    if (sigaction(SIGUSR1, &action, NULL) == -1)
        fail("sigaction");
    if (sigprocmask(SIG_BLOCK, &held, &old) == -1)
        fail("sigprocmask");
    if (raise(SIGUSR1) != 0 || raise(SIGUSR1) != 0)
        fail("raise");
    if (sigpending(&pending) == -1)
        fail("sigpending");
    int member = sigismember(&pending, SIGUSR1);
    if (member == -1)
        fail("sigismember");
    printf("SIGUSR1 pending: %s\n", member ? "yes" : "no");
    during_wait = old;
    if (sigdelset(&during_wait, SIGUSR1) == -1)
        fail("sigdelset");
    while (!ready) {
        if (sigsuspend(&during_wait) == -1 && errno != EINTR)
            fail("sigsuspend");
    }
    if (sigprocmask(SIG_SETMASK, &old, NULL) == -1)
        fail("restore mask");
    return EXIT_SUCCESS;
}

Build and run it with the following commands. Both raises occur while blocked. The program reports pending membership before the wait permits delivery.

bash
cc -std=c11 -Wall -Wextra -O0 -g pending_demo.c -o pending_demo
./pending_demo

2Combine unblocking and sleeping

sigsuspend() temporarily replaces the mask and waits as one atomic operation. Its mask must allow the desired signal. After a handler returns, sigsuspend() restores the mask from before the call and returns minus one with errno set to EINTR.

The loop tests ready while SIGUSR1 is blocked. It then unmasks only through the atomic wait. An unrelated handled signal can also wake it, so the condition needs a loop.

The two raises do not mean two future handler invocations. The flag answers whether work may exist, not how many events happened. Standard signal delivery order is unspecified.

In pending_demo.c, raising SIGUSR1 twice while blocked leaves one pending indication. sigsuspend temporarily permits delivery; mark_ready sets ready=1, and handler return restores the blocked mask.

  • states: [{"id": "blocked-empty", "label": "SIGUSR1 blocked; not pending; ready=0"}, {"id": "blocked-pending", "label": "SIGUSR1 blocked; one pending indication; ready=0"}, {"id": "handled", "label": "Handler returned; SIGUSR1 blocked again; ready=1"}]
  • transitions: [{"from": "blocked-empty", "to": "blocked-pending", "event": "raise(SIGUSR1) while blocked"}, {"from": "blocked-pending", "to": "blocked-pending", "event": "raise(SIGUSR1) while blocked"}, {"from": "blocked-pending", "to": "handled", "event": "sigsuspend allows SIGUSR1; handler runs and returns"}]

In a threaded application use pthread_sigmask() and coordinate masks across threads. Blocking in one thread does not stop another eligible thread receiving a process-directed signal. These sigprocmask() patterns assume one thread.

Wait without a gapBlocksignalTest flagDeliveryremainsblockedsigsuspendAtomicallyunblock andwaitHandlersets flagOld maskrestoredRecheckconditionBlocksignalTest flagDeliveryremainsblockedsigsuspendAtomicallyunblock andwaitHandlersets flagOld maskrestoredRecheckcondition
The blocked condition check leads directly into atomic unblocking and waiting.
06

Understand the delivery frame and EINTR

3 min read

Consider a read() waiting on terminal input. Linux puts the task to sleep. A caught signal becomes deliverable, and the task wakes to handle it. Your handler is user-space code, not a second program running on a separate CPU by default.

To enter the handler, Linux builds a signal frame in user memory. The frame carries saved registers, a saved mask, and the information needed for return. Registers hold the processor's working values, including the instruction address and stack pointer.

The Signal frames obey architecture-specific ABI rules. An AArch64 frame differs from an x86-64 frame. Do not copy a debugger's register offsets between them.

On handler return, a trampoline leads to rt_sigreturn, restoring the saved state. A trampoline is a small return stub supplied through the platform's signal machinery. Do not call sigreturn() directly or hand-build these frames in ordinary application code.

Going deeperWhere to inspect Linux signal machinery

In Linux source, kernel/signal.c implements much of signal generation, pending queues, selection, and dispositions. include/linux/sched/signal.h defines shared signal-related structures. A task has its own blocked mask and thread-pending state; a process also has shared pending state.

On arm64, arch/arm64/kernel/signal.c handles architecture-specific frame setup and restoration. Follow your target kernel's source and configuration. Register extensions can affect frame space, so a stack size copied from another architecture can be inadequate.

When a system call returns minus one with EINTR, a handled signal interrupted that operation. You must decide whether to retry, finish shutdown, or recompute a timeout. Blind retry can prevent a service from responding to its stop flag.

Linux operation interrupted by a handler Effect of SA_RESTART
waitpid() waiting for a child Restarted when requested
read() on a terminal or pipe before any bytes transfer Restarted when requested
Blocking open() of a FIFO Restarted when requested
select(), poll(), epoll_wait() Return EINTR rather than restarting
nanosleep() Returns EINTR; inspect remaining time
Socket operations with configured receive/send timeouts Not restarted under the documented timeout rules

Consult signal(7) for the full Linux list. Ordinary disk I/O is not treated like a terminal waiting for input. A successful partial read or write returns a positive byte count, not EINTR; advance by that count before continuing.

SA_RESTART is a property of the delivered signal's action. It does not make a blanket promise for every call. Higher-level functions can add buffering and their own retry policy, so identify the actual interface that failed.

For timed event loops, keep an absolute deadline using a monotonic clock, which does not jump with wall-clock changes. Recompute the remaining duration after interruption. Restarting the original relative timeout each time can extend a supposedly bounded wait indefinitely.

Enter and leave a handlerNormal codeKernelHandlerBlocking readPrepare signal frameEnter handlerReturn viart_sigreturnRestore executionstate1. Normal code → KernelBlocking read2. Kernel → KernelPrepare signal frame3. Kernel → HandlerEnter handler4. Handler → KernelReturn via rt_sigreturn5. Kernel → Normal codeRestore execution state
A user-space signal frame lets the kernel enter a handler and later restore execution.
07

Reap children and keep mysh alive

5 min read

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.
08

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.
09

Diagnose common signal mistakes

3 min read

Distinguish an incorrectly ignored signal from a flag set while the loop stays in a restarted read.

Symptom Likely cause Diagnose Fix
Handler seems silent Signal blocked, ignored, or delivered elsewhere Inspect masks and dispositions Correct setup before creating workers
Child ignores Ctrl-C Inherited SIG_IGN or blocked SIGINT Inspect child signal state Reset disposition and intended mask before exec
Intermittent ECHILD Handler and main code both wait Trace wait calls in all paths Choose one status owner or block competing delivery
Zombies accumulate Only one reap per notification Inspect child states and reaping loop Drain waitpid with WNOHANG
Shutdown hangs Unsafe handler call or blocking I/O Stop in GDB and inspect the stack Defer cleanup; use a wakeup mechanism
Wait misses an event Separate condition test and sleep Review the timing gap Use blocked test plus sigsuspend or pselect

Set target to your running mysh PID. These commands inspect identity and signal fields.

bash
target=12345   # Replace with your mysh PID.
ps -o pid,ppid,pgid,tpgid,stat,comm -p "$target"
grep -E '^(Name|Pid|PPid|SigQ|SigPnd|ShdPnd|SigBlk|SigIgn|SigCgt):' "/proc/$target/status"

The PID is a placeholder. SigPnd shows thread-pending bits and ShdPnd shows process-shared pending bits. SigBlk, SigIgn, and SigCgt show blocked, ignored, and caught masks. Bit position signal_number - 1 identifies the signal; use the target's numbers when decoding.

For each thread, inspect /proc/PID/task/TID/status, where TID identifies that thread.

strace can reveal signal delivery alongside actual waits. Attach to your own shell using the next command, subject to the system's tracing permissions. -f follows children, and tracing wait4 covers the Linux call commonly used underneath waitpid().

bash
strace -f -e trace=rt_sigaction,rt_sigprocmask,wait4,waitid -p "$target"

Tracing changes timing and can hide races. Repeat controlled tests. In GDB, info signals shows handling policy; handle SIGINT stop print pass requests stopping while still passing SIGINT to the program when continued.

On a small BusyBox root filesystem, full ps options and strace may be absent. Read proc files directly or reproduce the issue in a development image with matching binaries. A process stuck in an uninterruptible kernel wait may not disappear immediately after SIGKILL; the signal cannot instantly unwind arbitrary driver code.

Inspect the whole pathVerifytargetPID andforegroundgroupCheckdispositionDefault,ignored, orcaughtInspectmasksBlocked andpendingbitsTracedeliverystrace orGDBFind waitownerCheck forcompetingreapersVerifytargetPID andforegroundgroupCheckdispositionDefault,ignored, orcaughtInspectmasksBlocked andpendingbitsTracedeliverystrace orGDBFind waitownerCheck forcompetingreapers
Debug signal failures by checking the target, disposition, mask, delivery, and status owner.
10

Accept signals in an event loop

4 min read

mysh needs keyboard input and child notifications. A flag alone does not wake a thread blocked on unrelated input. Polling that flag wastes CPU time and drains a battery without fixing the underlying waiting problem.

One option is sigwaitinfo(). Block the selected signals before they can arrive, then pass the same set to the wait. The function returns a signal number and fills siginfo_t. It consumes the pending notification rather than calling a handler.

sigtimedwait() adds a relative timeout using struct timespec, whose fields specify seconds and nanoseconds. A zero duration polls pending state. Timeout returns minus one with EAGAIN; interruption by a different caught signal can return EINTR. A synchronous receiver can use ordinary logging after return because it is running normal code.

1Choose one receiver for each signal

Do not let a handler, a synchronous waiter, and signalfd compete for the same notification. In a threaded service, block the selected process-directed signals in every thread, preferably before creating threads. A dedicated receiver can then accept them deliberately.

Linux signalfd() exposes selected pending signals through a file descriptor, the small integer handle used by read() and I/O waiting functions. Keep selected signals blocked from asynchronous delivery. signalfd cannot receive SIGKILL, SIGSTOP, or synchronous hardware faults such as a faulting instruction's SIGSEGV.

This normal-code setup fragment returns a nonblocking signal descriptor and saves the old mask for later restoration. Its owner must keep SIGCHLD blocked while using the descriptor. Include _POSIX_C_SOURCE 200809L before headers in the source file.

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

static int open_child_notifications(sigset_t *old_mask)
{
    sigset_t selected;
    if (sigemptyset(&selected) == -1 ||
        sigaddset(&selected, SIGCHLD) == -1)
        return -1;
    if (sigprocmask(SIG_BLOCK, &selected, old_mask) == -1)
        return -1;
    int fd = signalfd(-1, &selected, SFD_NONBLOCK | SFD_CLOEXEC);
    if (fd == -1) {
        int saved_errno = errno;
        (void)sigprocmask(SIG_SETMASK, old_mask, NULL);
        errno = saved_errno;
    }
    return fd;
}

SFD_CLOEXEC closes the descriptor during a successful exec. That does not clear the child's inherited signal mask. Restore the intended child mask before execution, as with the handler-based shell.

2Consume records, then drain actual child state

Add the descriptor to select(), poll(), or Linux epoll, which wait for descriptors ready for I/O. When ready, read one or more struct signalfd_siginfo records. Each successful read returns a whole number of records. The structure is different from siginfo_t; its signal number field is ssi_signo.

Read until EAGAIN; handle EINTR without interpreting an unfilled buffer. SIGCHLD still coalesces. Drain waitpid(-1, &status, WNOHANG) in the loop, then log PIDs and statuses and update jobs there.

For the portable alternative, a Create it before installing the handler, make both ends nonblocking, and prevent unintended inheritance across exec. The handler writes a byte and preserves errno; the loop drains bytes and then child statuses.

A full notification pipe is already readable, so an EAGAIN write can be treated as an existing wakeup. Retry a one-byte write interrupted with EINTR. Keep both ends valid while handlers can run, and stop delivery before closing them. Otherwise a write with no readers can generate SIGPIPE.

The byte means inspect state, not one child exited. A pipe can merge wakeups without losing retained child wait statuses. Avoid the separate flag-test then select() race by relying on the readable pipe, or use pselect() with atomic mask replacement.

For an embedded supervisor, signalfd trades Linux dependence and a descriptor for simpler ownership. A self-pipe adds two descriptors and careful lifecycle handling but works beyond Linux. Neither mechanism makes signal latency deterministic. Select based on portability, resource limits, and how the service already waits for work.

Signals become loop workChild exitsNotification routesignalfd orself-pipeDescriptorreadyNormalevent loopDrainstatusesReport andupdateLogging andjob tableChild exitsNotification routesignalfd orself-pipeDescriptorreadyNormalevent loopDrainstatusesReport andupdateLogging andjob table
The event loop consumes wakeups and owns child status collection, logging, and job updates.
11

Try it

1 min read

Use the lab, mysh v2: Ctrl-C, child reaping, and signal-driven events, to extend the shell from the previous lesson. Show that the parent survives Ctrl-C, the foreground child receives it, and repeated short-lived children leave no zombies. In this lesson's practice pack, reason through blocked delivery, EINTR, status ownership, and the difference between a raised SIGSEGV and a hardware fault. Then choose a self-pipe or signalfd design and explain how your event loop prints child results without unsafe handler logging.

Build signal confidenceSafehandlerCtrl-CpolicyChildreapingEvent-loopownershipFaultdiagnosticsSafehandlerCtrl-CpolicyChildreapingEvent-loopownershipFaultdiagnostics
Practice progresses from safe handlers to shell behavior, event-loop ownership, and fault diagnostics.

Key takeaways

  • A signal can remain pending before any handler runs.
  • Standard signals coalesce; one notification can represent several child exits.
  • Use sigaction to select the handler, temporary mask, and restart policy.
  • Handlers must use async-signal-safe operations and preserve errno when needed.
  • Block before testing shared state; sigsuspend atomically unmasks and waits.
  • Give child status collection one owner, and reset inherited child signal policy.
  • Realtime signals carry queued values but have finite queue capacity.
  • signalfd moves signal processing into normal event-loop code on Linux.

Reflect

  1. Explain to a colleague, in two sentences: describe signal generation, pending state, delivery, and default actions.
  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.

Practise this lessonExercises, quiz, interview preparation and spaced review

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

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