Lesson 42 of 50
cSignal Handling (`signal.h`)
9 mins
Course progress84%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 42 of 50
c9 mins
Keep these ideas in mind as you work through the lesson.
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("
Caught Ctrl‑C, exiting gracefully...
");
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;
}