I have a program in C. I wish for it to always exit cleanly with exit code of 0 when it gets a SIGTERM. What is the earliest place I can register the signal handler? I added it at the top of my main()
, but I worry it might get a sigterm just before the signal registers.
Is it possible to register a signal handler even earlier?
Yes you can. Using platform specific initializers such as gcc's __attribute((constructor))
. But that's hardly a robust solution.
If you wish to "to always exit cleanly with exit code of 0 when it gets a SIGTERM", then instruct the process-spawning code to start with SIGTERM
blocked.
Your main
can then register a signal handler and unblock SIGTERM
(with sigprocmask
or pthread_sigmask
, at which point the signal handler will run immediately if it had been received at any point in between process creation up to the signal-unblocking call.
Essentially, it will defer the delivery of the signal up to a point where you're ready too handle it.
(Note that if you start the process with the signal ignored rather than blocked, then any instance of the signal received up to unignoring the signal will have been lost, as if they never happened. That would seem to go against your stated requirement.)