linux-sysprog · beginner · ~10 min

Classify a signal into an action

The dispatch-table pattern for signal handling.

Challenge

You're inside a server's signal-handling loop. The signals arrive via signalfd. Implement int classify_signal(int sig) that returns:

  • 0 for SIGINT (2) and SIGTERM (15) — clean shutdown
  • 1 for SIGHUP (1) — config reload
  • 2 for SIGCHLD (17) — child reaper
  • -1 for any other signal

Use the literal signal numbers above (so the test fixture doesn't need to include <signal.h>).

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

Signal number.

Output format

0/1/2/-1.

Constraints

No <signal.h>; the numbers are baked into the spec.

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.