Handling a termination request with signal
suggest changeThe following ISO C example records a SIGINT request in the handler and performs normal cleanup after control returns to the main program:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
static volatile sig_atomic_t stop_requested;
static void request_stop(int signal_number)
{
(void)signal_number;
stop_requested = 1;
}
int main(void)
{
if (signal(SIGINT, request_stop) == SIG_ERR) {
fputs("Could not install the SIGINT handler\n", stderr);
return EXIT_FAILURE;
}
while (!stop_requested) {
/* Perform work without blocking indefinitely. */
}
puts("Stopping");
return EXIT_SUCCESS;
}
The handler does not call printf or other general-purpose library functions because they are not safe in a strictly conforming asynchronous signal handler. volatile sig_atomic_t is appropriate for this limited communication pattern; it is not a general replacement for atomics or thread synchronization.
Behavior and persistence of handlers installed with signal vary among environments. Programs targeting POSIX commonly use sigaction instead, but sigaction is not part of ISO C.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents