linux-sysprog · beginner · ~10 min

Classify a signal into an action

The dispatch-table pattern for signal handling.

Challenge

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.

Task

Implement int classify_signal(int sig) that returns an action code for sig.

Input

  • sig: a signal number. Use these literal values (no <signal.h> needed):
    • SIGHUP = 1, SIGINT = 2, SIGTERM = 15, SIGCHLD = 17.

Output

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.

Example

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

Edge cases

  • Any signal not in the list (including 0) returns -1.

Why this matters

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.

Input format

A signal number sig (SIGHUP=1, SIGINT=2, SIGTERM=15, SIGCHLD=17).

Output format

0 (shutdown) for SIGINT/SIGTERM, 1 (reload) for SIGHUP, 2 (reap) for SIGCHLD, -1 otherwise.

Constraints

Use the literal signal numbers; no <signal.h>. Unknown signals return -1.

Starter code

int classify_signal(int sig) { /* TODO */ return -1; }

Common mistakes

Returning 1 for SIGINT (mistakenly thinking it's a reload).

Edge cases to handle

Unknown signal (-1). Signal 0 (-1).

Complexity

O(1).

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.