Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graceful termination of Qt application by unix signal

I have problems saving settings in my application. This is done in the destructors of the relevant objects. It is a launcher and a termination by shutdown is a standard case. The only way the application actually saves the setting is by manual closing it or session shutdown (on cinnamon at least, I guess this just closes all windows). Even sudo reboot prevents the Qt application from unwinding the objects on the stack. Terminating by killall -s <signal> <app> has the same effect for SIGINT, SIGKILL and SIGTERM. How can I force my qt app to gracefully terminate at on SIGTERM? aboutToQuit is not emitted either.

like image 912
ManuelSchneid3r Avatar asked Oct 12 '15 13:10

ManuelSchneid3r


1 Answers

There is a minimal set of functions a unix signal handler is allowed to call. They are called async-signal-safe functions. Calling everything else, including every Qt function, results in undefined behavior.

Still there is a way to handle unix signals in Qt. The way uses the self-pipe-trick and is described in the Qt docs article "Calling Qt Functions From Unix Signal Handlers".

Basically you open a pipe and whenever you get a signal you ::write(...) (this is a async-signal-safe function) to the pipe. On the other end you listen to the pipe using a QSocketNotifier. For the implementation details check the Qt article mentioned above.

like image 74
ManuelSchneid3r Avatar answered Nov 14 '22 22:11

ManuelSchneid3r