Signal handler
- C course
- Advanced
- Lesson 14/83
- 5 min
Learn to catch signals with the signal function.
The signal function
signal(sig, handler) registers a handler for a signal. handler is a pointer to a function that takes the signal number and returns void.
For example, signal(SIGUSR1, handler) calls handler when SIGUSR1 arrives. Inside the handler you should only do safe operations; the signal can arrive at any time. signal is simple but its behavior varies across systems; production code prefers sigaction.
Sending signals with raise
raise(sig) sends the sig signal to the calling process. It has the same effect as kill(getpid(), sig).
The handler interrupts the process flow when the signal arrives and is called. When the handler returns, the process resumes where it was. raise is synchronous: the call waits until the handler returns. So the line after raise(SIGUSR1) runs after the handler finishes. Ideal for testing.
Practice Catch a signal
Define global int caught = 0;. Write void handler(int sig) with caught = 1;. Register with signal(SIGUSR1, handler);. Send with raise(SIGUSR1); and print with printf("caught=%d\n", caught);.
Starter code
#include <stdio.h>
#include <signal.h>
int caught = 0;
// Write handler function
// Register with signal
// Raise and print
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <signal.h>
int caught = 0;
void handler(int sig) {
caught = 1;
}
int main(void) {
signal(SIGUSR1, handler);
raise(SIGUSR1);
printf("caught=%d\n", caught);
return 0;
}Expected output
caught=1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match handler concepts
| Term | Meaning |
|---|---|
signal |
Registers handler |
raise |
Signal to self |
handler |
Handler function |
SIGUSR1 |
User signal |
2 What does raise(SIGUSR1) do?
- Sends to another process
- Sends to the caller Correct answer
- Ignores the signal
- Blocks the signal
Explanation: raise sends the signal to the calling process.
3 Handler registration
signal(SIGUSR1, ____);
signal(SIGUSR1, handler);
Explanation: The handler function is registered for SIGUSR1.