C Signal Handling
In this page:
What is a Signal?
A signal is an asynchronous notification the operating system delivers to a running process to report an event like an illegal instruction, a segmentation fault, or the user pressing Ctrl+C, interrupting the program's normal flow so it can react to that event.
Example: What is a Signal?
#include <stdio.h>
#include <signal.h>
int main() {
printf("Signals notify a process of events like Ctrl+C");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
The signal() Function
The signal() function registers a custom handler function to run whenever a specific signal (identified by a constant like SIGINT or SIGSEGV) is delivered to your process, letting you replace the operating system's default behavior — which is usually to terminate the program outright — with your own response.
Example: The signal() Function
#include <stdio.h>
#include <signal.h>
void handler(int sig) {
printf("Caught signal %d", sig);
}
int main() {
signal(SIGINT, handler);
raise(SIGINT);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Catching SIGINT
SIGINT is the signal generated when the user presses Ctrl+C in the terminal running your program, and catching it with a custom handler lets your program close open files, free resources, and shut down gracefully instead of being killed abruptly mid-operation.
Example: Catching SIGINT
#include <stdio.h>
#include <signal.h>
void handleSigint(int sig) {
printf("Ctrl+C caught, cleaning up");
}
int main() {
signal(SIGINT, handleSigint);
raise(SIGINT);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Ignoring Signals
Passing the special value SIG_IGN as the handler argument to signal() tells the operating system to simply discard a specific signal whenever it arrives, rather than acting on it — a way to make a section of your program deliberately immune to an interrupt like SIGINT.
Example: Ignoring Signals
#include <stdio.h>
#include <signal.h>
int main() {
signal(SIGINT, SIG_IGN);
printf("SIGINT will now be ignored");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Raising Signals with raise()
The raise() function lets a program generate and send a signal to itself programmatically, which is useful for testing how your own signal handlers behave, or for deliberately triggering an internal fault-handling path from within the program's own logic.
Example: Raising Signals with raise()
#include <stdio.h>
#include <signal.h>
void handler(int sig) {
printf("Handler triggered by raise()");
}
int main() {
signal(SIGTERM, handler);
raise(SIGTERM);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: