Signals in C
A handler runs on interrupt, and it may only touch async-signal-safe things.
#define _POSIX_C_SOURCE 200809L
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
static volatile sig_atomic_t stop_requested = 0;
static void on_signal(int signum) {
(void) signum;
stop_requested = 1;
}
int main(void) {
struct sigaction action;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
action.sa_handler = on_signal;
if (sigaction(SIGINT, &action, NULL) != 0) {
perror("sigaction");
return 1;
}
printf("working, press ctrl-c\n");
for (int i = 0; i < 5 && !stop_requested; i++) {
sleep(1);
}
printf("stopped %s\n", stop_requested ? "early" : "normally");
return 0;
}
How it works
sigactionis POSIX, so the feature macro comes first.- The flag it sets must be
volatile sig_atomic_t. - Do the real work back in the main loop, not in the handler.
Keywords and builtins used here
NULLforifintmainon_signalreturnsig_atomic_tsigactionstaticstructvoidvolatile
The run, in numbers
- Lines
- 31
- Characters to type
- 591
- Tokens
- 149
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 85 seconds.
Step 4 of 4 in Processes & signals, step 10 of 14 in Systems programming.