M310 M310 - 1 year ago 89
C Question

What is best practice for signal handling in production multi-threaded program on Linux?

I'm writing a multi-threaded program that shall run on a Linux system. I want to be sure that, if the program was in a reliable running condition (i.e. no segmentation faults, no abort, etc...), on exit it finalises a file writing some trailing information. To do so I want to handle the termination signals in order to trigger a graceful shut down.
Since it is a multi-threaded program all the signals are masked for all the threads but the main, which call sigwait on a signal set filled only with the termination signals. So all other signals are handled by their default action.

Is this a good practice, or I should provide a custom action for every signal?

nos nos
Answer Source

Is this a good practice,

Yes absolutely. Handling termination signals in a multi-threaded environment any other way(by not having a single thread responsible for them) is virtually impossible.

or I should provide a custom action for every signal?

No. You'd normally want to handle SIGINT, SIGTERM and SIGHUP. SIGKILL can't be handled, and I'd leave SIGQUIT alone so it could be used to core-dump the application.