C Signals

What Is a Signal in C?
A signal is a simple event notice delivered to a program. Common examples are an interrupt request or an abnormal termination request. The <signal.h> header lets a beginner install a handler, ignore a signal, or restore the default action.
The two functions in this series are signal() and raise(). Use signal() to choose the disposition, then use raise() to test that choice inside the same program.
Keep handlers tiny. The safest beginner pattern is to set a volatile sig_atomic_t flag and continue in normal code after the signal returns.
Common Signal Numbers
| Macro | Typical meaning |
|---|---|
SIGINT | Interactive interrupt request. |
SIGTERM | Termination request. |
SIGABRT | Abnormal termination request. |
SIGFPE | Erroneous arithmetic operation. |
SIGSEGV | Invalid memory access. |
SIGILL | Invalid instruction. |
Also remember the disposition macros: SIG_DFL for the default action, SIG_IGN to ignore the signal, and SIG_ERR for a failed signal() call.
The Tiny Handler Pattern
- Declare a flag. Use
volatile sig_atomic_tso the handler can update it safely. - Write a small handler. Set the flag and return. Do not call
printformallocthere. - Install with signal(). Check for
SIG_ERRbefore continuing. - Test with raise(). Then read the flag in normal code.
Starter: Install, Raise, and Read a Flag
#include <stdio.h>
#include <signal.h>
volatile sig_atomic_t got = 0;
void on_sigint(int sig) {
(void)sig;
got = 1;
}
int main(void) {
if (signal(SIGINT, on_sigint) == SIG_ERR) {
printf("install failed\n");
return 1;
}
if (raise(SIGINT) != 0) {
printf("raise failed\n");
return 1;
}
printf("got = %d\n", (int)got);
return 0;
} How It Works
- Install the handler.
signal(SIGINT, on_sigint)chooses the response for SIGINT. - Raise the signal.
raise(SIGINT)asks the current program to handle it now. - Keep the handler tiny. Only the flag is updated.
- Print in normal code. After raise returns,
maincan safely report the flag.
Open the Function Guides
Frequently Asked Questions
Browse signal.h functions
Open raise() and signal() with full examples.
8 people found this page helpful
