问题描述
我有一个QApplication,根据命令行参数,有时实际上没有GUI窗口,但只是运行没有GUI。在这种情况下,如果CTRL-C命中,我想优雅地关闭它。基本上我的代码看起来像这样:
I have a QApplication that, depending on command line parameters, sometimes doesn't actually has a GUI window, but just runs without GUI. In this case, I want to shut it down gracefully if CTRL-C was hit. Basically my code looks like this:
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
... // parse command line options
if (no_gui) {
QObject::connect(&app, SIGNAL(unixSignal(int)),
&app, SLOT(quit()));
app.watchUnixSignal(SIGINT, true);
app.watchUnixSignal(SIGTERM, true);
}
...
return app.exec();
}
但是,这不起作用。 CTRL-C似乎被捕获(应用程序不会被杀死),但它也不退出。
However, this does not work. CTRL-C seems to be caught (the application doesn't get killed), but it also doesn't exit. What am I missing?
推荐答案
由于没有记录, QApplication :: watchUnixSignal
不应该使用。并且,从阅读代码,它使用glib事件分派器(这是Linux上的默认值)时无法正常工作。
As it isn't documented, QApplication::watchUnixSignal
shouldn't be used. And, from reading the code, it will not work properly when using the glib event dispatcher (which is the default on Linux).
但是,一般来说,可以在Qt应用程序中安全地捕获Unix信号,您只需要自己写一点代码。在文档中甚至有一个例子 - 。
However, in general you can safely catch Unix signals in Qt applications, you just have to write a bit of the code yourself. There is even an example in the documentation - Calling Qt Functions From Unix Signal Handlers.
这篇关于QApplication:如何正常关闭Ctrl-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!