Graceful termination of Qt application by unix signal

我与影子孤独终老i 提交于 2019-12-10 15:12:24

问题


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.


回答1:


Unfortunately the internet spreads a lot of plain wrong information, ways that result in undefined behaviour. 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 beghaviour. 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.



来源:https://stackoverflow.com/questions/33083038/graceful-termination-of-qt-application-by-unix-signal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!