在关闭QCoreApplication之前进行清理 [英] Clean up before closing the QCoreApplication

查看:552
本文介绍了在关闭QCoreApplication之前进行清理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于控制台的QCoreApplication,它具有计时器并进行套接字通信,还使用锁定的互斥锁.

I have a console-based QCoreApplication which has timers and does socket communication and also uses locked mutex.

当我手动关闭应用程序时,出现错误,提示某些互斥锁已锁定,并且超时.当用户关闭控制台应用程序时,有什么方法可以清除它?

When I close the application manually, it gives error saying some mutex is locked and it is timed out. Is there any way I can do clean up in a console application when user closes it?

推荐答案

清除程序应由析构函数和子代关系处理.

Cleanup should be handled by destructors and child-parent relationship.

使您的主对象(主对象)成为QApplication的子对象,以便在QApplication之前将其所有子对象销毁.

Make your master object (the one in the main) a child of QApplication so it is destructed with all its childs before QApplication is.

确定要杀死所有线程吗?如果它是带有事件循环的线程,请确保在调用QThread::wait()

Are you sure you killed all your threads? If it is a thread with an eventloop be sure to call QThread::quit() to exit the eventloop before you call QThread::wait()

您也可以使用void QApplication::qAddPostRoutine ( QtCleanUpFunction ptr ) 进行一些特殊的清理.

You can also use the void QApplication::qAddPostRoutine ( QtCleanUpFunction ptr ) to do some special cleanup.

要调试这些消息,可以使用QtMsgHandler qInstallMsgHandler ( QtMsgHandler h )并编写自己的消息处理程序以捕获这些警告.如果可以模拟问题,则可以在消息上设置断点,并在消息来自的堆栈上查看.

For debugging those messages you can use QtMsgHandler qInstallMsgHandler ( QtMsgHandler h ) and write your own message handler to capture those warnings. If you can simulate the problem you can set a breakpoint on the message and see on the stack where the message is coming from.

void debugMessageHandler( QtMsgType type, const char *msg ){
    if(QString(msg).contains( "The message you can see in the console" )){
        int breakPointOnThisLine(0);    
    }

    switch ( type ) {
        case QtDebugMsg:
            fprintf( stderr, "Debug: %s\n", msg );
            break;
        case QtWarningMsg:
            fprintf( stderr, "Warning: %s\n", msg );
            break;
        case QtFatalMsg:
            fprintf( stderr, "Fatal: %s\n", msg );
            abort();
    }
}


为了清理析构函数和父子关系,您可以捕获控制台关闭信号,并向应用程序实例调用QCoreApplication::exit().

#include <csignal>
#include <QtCore/QCoreApplication>
using namespace std;

struct CleanExit{
    CleanExit() {
        signal(SIGINT, &CleanExit::exitQt);
        signal(SIGTERM, &CleanExit::exitQt);
        signal(SIGBREAK, &CleanExit::exitQt) ;
    }

    static void exitQt(int sig) {
        QCoreApplication::exit(0);
    }
};


int main(int argc, char *argv[])
{
    CleanExit cleanExit;
    QCoreApplication a(argc, argv);
    return a.exec();
}

这篇关于在关闭QCoreApplication之前进行清理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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