Signal safety and reentrant functions
What you'll learn: How to write signal handlers that don't crash your program by using only "async-signal-safe" functions.
The interrupted chef
Imagine you are a chef (the CPU) chopping onions for a soup. Suddenly, a fire alarm (a signal) goes off. You drop everything, run to grab the fire extinguisher, and then return to the onions.
Now, imagine that just as the alarm rang, you were halfway through updating the restaurant's inventory list. If your "fire alarm procedure" also tries to update that same inventory list, the data will become a garbled mess because you were interrupted mid-sentence.
In C, a signal can interrupt your program at any nanosecond—even in the middle of a function call like printf().
The danger of non-reentrant functions
A reentrant function is one that can be safely interrupted and then "re-entered" by a signal handler without causing errors.
Most standard library functions, including printf() and malloc(), are not reentrant. They often use global data structures or internal locks. If your main program is inside printf() and a signal triggers another printf(), the internal state of the output buffer might corrupt, leading to a deadlocked program or a mysterious crash.
Async-signal-safe functions
To stay safe, signal handlers should only call functions explicitly labeled as async-signal-safe. These are designed to be atomic or to avoid shared state entirely. Instead of printf(), we use the low-level write() system call.
#include <unistd.h>
#include <signal.h>
// SAFE: write() is async-signal-safe
void safe_handler(int signum) {
const char msg[] = "Signal received safely!\n";
write(STDOUT_FILENO, msg, sizeof(msg) - 1);
}
// UNSAFE: printf() uses internal buffers and locks
void unsafe_handler(int signum) {
// printf("This could cause a deadlock!");
}
int main() {
struct sigaction sa = {0};
sa.sa_handler = safe_handler;
sigaction(SIGINT, &sa, NULL);
while(1) {
// Main loop doing work
}
return 0;
}
When writing handlers, keep them "small and simple." The best practice is often to just set a global flag of type volatile sig_atomic_t and handle the actual logic back in your main loop.
Key takeaway
Only use async-signal-safe functions (like write) inside signal handlers to avoid data corruption and deadlocks.