I'm developing a POSIX daemon which reads from a database from time to time. I'd like to close the connection when SIGTERM arrives (e.g. when the system shuts down).
When the signal handler is called, is the main() paused until the handler finishes its job? If so and the handler calls exit(), is the main() execution aborted (immediately and atomically)? If not so, is it a "good idea" to just not handle SIGTERM (from the connection's POV)?
Update: Why to pause main(): Let's say:
- SIGTERM arrives and the signal handler is called. It closes the connection and frees its memory.
- Just after that the non-paused main() says that it's time to fetch data from the DB.
That would result in a dereference of a invalid pointer (or at least in an operation on a closed connection).
Best How To :
Signals interrupt process execution; they do not execute in parallel. So if there is only a single thread in the process, it will be suspended while the signal handler is executing. (If the process is multithreaded, only one thread will be interrupted and the others will continue executing.)
However, there are few guarantees about the state of the process at the moment that it is interrupted. It may be interrupted during execution of a standard library function at a point where internal datastructures are in an inconsistent state. Only a small number of system interfaces (the complete list is here) may be called during execution of a signal handler; in particular, memory management functions such as
free may not be called, and it is quite likely that shutting down a database connection will involve calling
shutdown are async-signal-safe.
exit is not (but
It is possible for a signal handler to modify the value of a global variable, which can be polled periodically (such a variable must be declared
volatile) but ensuring that the termination is recognized by the main process is not easy.
Although the desire to cleanly shutdown a database connection is understandable, a database must be resilient to uncleanly terminated connections. Clients crash at unexpected moments and network connections can fail; a database must be robust in the face of such occurrences. A client receiving a SIGTERM is simply one of a long list of these possibilities, and it is probably best to simply rely on the database server correctly handling the shutdown.