Module 2 · Lesson 32 of 131

Signal mistakes and the event loop

Diagnose signal bugs with proc and strace, and accept signals in a normal event loop using signalfd, sigwaitinfo, or a self-pipe.

  • Beginner to advanced
  • 6 min read
  • 17 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 2 objectives
  • Diagnose signal failures by inspecting masks, dispositions, and delivery with proc and strace
  • Accept signals synchronously in a normal event loop with signalfd, sigwaitinfo, or a self-pipe
Video coming soonSignal mistakes and the event loop
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from SIGCHLD and queued signals
  • 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.
01

Diagnose common signal mistakes

3 min read

Reaping and queued signals are in place, yet signal bugs and delivery races still appear in a real shell. This lesson answers how to diagnose signal mistakes and accept signals in a normal event loop.

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

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

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

  • signalfd moves signal processing into normal event-loop code on Linux.
  • Separate sending, pending state, and response when debugging, and inspect masks and dispositions under /proc/PID/status
  • A self-pipe byte means inspect state, not one child exited; make both ends nonblocking and stop delivery before closing them
Reflect
  1. Explain to a colleague, in two sentences: diagnose signal failures by inspecting masks, dispositions, and delivery with proc and strace
  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