13.5. Performing Proper Signal Handling
Your program needs to handle asynchronous signals.
On Unix systems, it is often necessary to perform some amount of signal handling. In particular, if a program receives a termination signal, it is often desirable to perform some kind of cleanup before terminating the program—flushing in-memory caches to disk, recording the event to a log file, and so on. Unfortunately, many programmers do not perform their signal handling safely, which of course leads to possible security vulnerabilities. Even more unfortunate is that there is no cookie-cutter solution to writing safe signal handlers. Fortunately, following some easy guidelines will help you write more secure signal-handling code.
- Do not share signal handlers.
Several signals are normally used to terminate a program, including
SIGINT(to name but a few). It is far too common to see code like this:
signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); signal(SIGQUIT, signal_handler);
Such code is unsafe because while
signal_handler( )is handling a
SIGTERMthat has been delivered to the process, a
SIGINTcould be delivered to the same function. Most programmers have a tendency to write their signal handlers in a non-reentrant fashion because the same signal will not be delivered to the process again until the first handler returns. In addition, many programmers write their code under the false assumption that no signals can be delivered while a ...