linux-sysprog · intermediate · ~15 min

Count raised signals

Observe repeated synchronous delivery.

Challenge

Each synchronous raise() runs the handler exactly once, so raising a signal twice increments a counter to 2. Demonstrate that.

Task

Implement int raise_twice(void) that installs a SIGUSR1 handler which increments a counter, calls raise(SIGUSR1) twice, and returns the counter.

Input

None.

Output

2 — the counter after two synchronous deliveries.

Example

raise_twice()   ->   2

Rules

  • Use a static volatile sig_atomic_t counter.
  • Install the handler before raising.

Input format

None.

Output format

2 — the handler count after raising SIGUSR1 twice.

Constraints

Use a sig_atomic_t counter; install the handler first.

Starter code

#include <signal.h>

int raise_twice(void) {
    /* TODO */
    return 0;
}

Common mistakes

Calling non-reentrant functions (like printf or malloc) inside signal handlers; neglecting sig_atomic_t or volatile qualifier for shared flags.

Edge cases to handle

Multiple instances of the same signal queued together; signal arriving while handler is already active; interrupted system calls (EINTR).

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