linux-sysprog · intermediate · ~15 min

Catch Ctrl-C

Catch SIGINT to shut down gracefully.

Challenge

Installing a SIGINT handler turns Ctrl-C from instant termination into a flag your program can check and shut down cleanly. Demonstrate the catch.

Task

Implement int catch_sigint(void) that installs a SIGINT handler (which sets a flag), raises SIGINT, and returns the flag.

Input

None.

Output

1 — the flag set by the handler, proving SIGINT was caught rather than fatal.

Example

catch_sigint()   ->   1

Rules

  • Install the handler before raising SIGINT, or the default action terminates the process.
  • Use a static volatile sig_atomic_t flag.

Input format

None.

Output format

1 once the SIGINT handler has run.

Constraints

Install the handler before raising; use a sig_atomic_t flag.

Starter code

#include <signal.h>

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

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