Allows a program to catch or ignore OS signals such as SIGINT (Ctrl+C) and SIGSEGV (segfault).
Include: #include <signal.h> | Compile: gcc -Wall -o prog prog.c
| Name | Prototype / Value | Description |
|---|---|---|
| signal | void (*signal(int sig, void (*handler)(int)))(int) | Install a signal handler |
| raise | int raise(int sig) | Send a signal to the current process |
| SIGINT | 2 | Interrupt (Ctrl+C) |
| SIGTERM | 15 | Termination request |
| SIGSEGV | 11 | Segmentation fault |
| SIGABRT | 6 | Abort signal |
| SIGFPE | 8 | Floating-point exception |
| SIG_DFL | 0 | Default handler |
| SIG_IGN | 1 | Ignore the signal |
Copy, save as demo.c, and compile with the command shown at the bottom.
#include <stdio.h>
#include <signal.h>
volatile int keep_running = 1;
void handle_sigint(int sig) {
(void)sig;
printf("\nCaught SIGINT. Shutting down...\n");
keep_running = 0;
}
int main(void) {
signal(SIGINT, handle_sigint);
printf("Press Ctrl+C to stop.\n");
long count = 0;
while (keep_running) count++;
printf("Counted to %ld before stopping.\n", count);
return 0;
}
/* Compile: gcc -Wall -o signal_demo signal_demo.c */