linux-sysprog · advanced · ~15 min

Count SIGUSR1 deliveries

Signal handler basics and the safe types/operations available inside one.

Challenge

Install a signal handler, raise SIGUSR1 a number of times, and count how often the handler ran.

Task

Implement int count_sigusr1(int times) that installs a SIGUSR1 handler, raises SIGUSR1 exactly times times via raise(SIGUSR1), then returns how many times the handler was invoked. No main — the grader calls it.

Input

One int argument times (>= 0) — how many signals to raise.

Output

The handler invocation count as an int (equal to times).

Example

count_sigusr1(0)    ->   0
count_sigusr1(1)    ->   1
count_sigusr1(10)   ->   10

Edge cases

  • times = 0: the handler never runs; return 0.

Rules

  • The counter must be a file-scope volatile sig_atomic_t; reset it before raising. Inside a handler, only async-signal-safe operations are allowed.

Input format

One int argument times (>= 0): how many times to raise SIGUSR1.

Output format

The handler invocation count as an int (equals times).

Constraints

Counter must be a file-scope volatile sig_atomic_t, reset before raising.

Starter code

#include <signal.h>

int count_sigusr1(int times) {
    /* TODO */
    return -1;
}

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