linux-sysprog · intermediate · ~12 min

Graceful SIGTERM — set a flag, cleanup in main

Combine handler + flag + main-loop check for clean termination.

Challenge

Implement two functions:

int install_graceful_term(void);
int do_work_until_term(int max_iters);
  • install_graceful_term installs a SIGTERM handler that sets the internal flag g_shutdown to 1.
  • do_work_until_term loops up to max_iters times. Each iteration is one unit of work. If g_shutdown == 1, break out of the loop and return the number of iterations actually completed. Otherwise return max_iters.

The harness raises SIGTERM after 3 iterations to verify graceful shutdown.

Why this matters

systemd sends SIGTERM, waits a grace period, then SIGKILL. Your service has one chance to clean up.

Starter code

#include <signal.h>
#include <stdio.h>
volatile sig_atomic_t g_shutdown = 0;
int install_graceful_term(void) {
    /* TODO */
    return -1;
}
int do_work_until_term(int max_iters) {
    /* TODO */
    return -1;
}

Background lessons

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