linux-sysprog · beginner · ~10 min
The dispatch-table pattern for signal handling.
Map an incoming signal number to the action a server should take. This is a pure classification function — the "signalfd loop" is just the framing; you only switch on the number.
Implement int classify_signal(int sig) that returns an action code for sig.
sig: a signal number. Use these literal values (no <signal.h> needed):Returns:
0 for SIGINT (2) or SIGTERM (15) — clean shutdown;1 for SIGHUP (1) — config reload;2 for SIGCHLD (17) — reap children;-1 for any other signal.classify_signal(2) -> 0 (SIGINT -> shutdown)
classify_signal(15) -> 0 (SIGTERM -> shutdown)
classify_signal(1) -> 1 (SIGHUP -> reload)
classify_signal(17) -> 2 (SIGCHLD -> reap)
classify_signal(9) -> -1 (unhandled)
classify_signal(0) -> -1
-1.signalfd turns signals into normal file descriptors — meaning your dispatch can be a switch in normal code, not an async-signal-safe handler. Demonstrate the switch.
A signal number sig (SIGHUP=1, SIGINT=2, SIGTERM=15, SIGCHLD=17).
0 (shutdown) for SIGINT/SIGTERM, 1 (reload) for SIGHUP, 2 (reap) for SIGCHLD, -1 otherwise.
Use the literal signal numbers; no <signal.h>. Unknown signals return -1.
int classify_signal(int sig) { /* TODO */ return -1; }
Returning 1 for SIGINT (mistakenly thinking it's a reload).
Unknown signal (-1). Signal 0 (-1).
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.