QApplication:如何正常关闭Ctrl-C [英] QApplication: How to shutdown gracefully on Ctrl-C

查看:1695
本文介绍了QApplication:如何正常关闭Ctrl-C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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信号,您只需要自己写一点代码。在文档中甚至有一个例子 - 从Unix信号处理程序调用Qt函数

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆