tags:

views:

764

answers:

2

Hello,

I have console based QCoreApplication in which has timers and does socket communication and also uses locked mutex . When i close console 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.?

Thanks, Suresh.

+1  A: 

you can connect to QCoreApplication::aboutToQuit signal and do the necessary clean up there.

Idan K
Hi Daniel,I tried this, but break point doesn't hit in the connected SLOT. documentation says aboutToQuit signal is emitted when quit on QCoreApplication is called. Does the closing of console application invoke quit()?Thanks,Suresh.
Suresh
+2  A: 

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

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

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()

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

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();
    }
}


In order to clean up with destructor and child-parent relation ship you can catch the console close signal and call QCoreApplication::exit() to the application instance.

#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();
}
TimW