liveBook · Manning

Signal handler

As explained in Modern C, Third Edition

A signal handler is a function invoked in response to a signal raised by an execution environment or program.

A signal handler is a function invoked when a signal interrupts ordinary execution. Signals can reflect a fault caused by the current instruction, such as division by zero, or an asynchronous event, such as a termination request. C provides a portable abstraction for both kinds of interrupt. section 19.6

Registering a handler

The interface includes `signal(int, sh_handler*)` to establish a handler and `raise(int)` to raise a signal. For example, a program can register a handler for `SIGINT`, an interactive attention signal. The handler receives the signal number, allowing it to record which condition occurred. section 19.6

TAKEAWAY: Keep the handler small. Record the interrupt condition in a global flag, return to the interrupted context, and do the substantive work there. Communication with a handler is limited to `volatile sig_atomic_t`, `atomic_flag`, or other lock-free atomic types. section 19.7

Figure 19.3 Control flow after an interrupt return jumps to the position where the interrupt occurred
figure

The control-flow diagram shows execution returning to the position where an interrupt occurred. section 19.6

How Modern C, Third Edition covers it

How deep it goes
Explains event timing and handler safety, then shows registration and counting interfaces without developing a general recovery procedure.
Examples
Uses fault and termination scenarios, signal-registration listings, and a per-signal counter guarded by `ATOMIC_LONG_LOCK_FREE`.
What it assumes
Assumes familiarity with C functions and ordinary control flow while distinguishing synchronous from asynchronous signals.
What you can do after
Operate/configure it by registering a handler that records a condition and leaves further work to interrupted code.
How it connects
Connects signal handling to interrupts, control flow, `setjmp`/`longjmp`, and lock-free atomic types.

Also explained in

Compare how 4 books explain signal handler →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.