Lesson 42 of 50 · c
Signal Handling (`signal.h`)
Duration: 9 mins
Signals are asynchronous notifications (e.g., SIGINT, SIGTERM). Use signal or the more robust sigaction to install handlers.
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
void handler(int sig) {
if (sig == SIGINT) {
printf("\nCaught Ctrl‑C, exiting gracefully...\n");
exit(0);
}
}
int main(void) {
struct sigaction sa = {0};
sa.sa_handler = handler;
sigemptyset(&sa.sa_mask);
sigaction(SIGINT, &sa, NULL);
while (1) { /* busy work */ }
return 0;
}