C++ application does not kill all processes on exit

二次信任 提交于 2020-01-14 05:29:37

问题


This is my main.cpp which starts the mainwindow:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    TabWindow w;
    w.show();
    return a.exec();
}

Even with the a.connect(...) I do not understand why myApplication.exe still runs after I close the mainwindow. Any suggestions on how I can fully end all processes after the quit button is clicked?

EDIT: The Qt Documentation says this: We recommend that you connect clean-up code to the aboutToQuit() signal, instead of putting it in your application's main() function. This is because, on some platforms, the QApplication::exec() call may not return.


回答1:


There's nothing wrong with your code. And your connect doesn't do anything.

Unless you call QGuiApplication::setQuitOnLastWindowClosed(true) somewhere, application should exit when the last window is closed. Probably you block event loop somewhere in your window code.




回答2:


Thanks to the comment posted by @ratchetfreak in my question, I figured out where the problem was.

In my MainWindow, I started a worker thread which was not terminated and thus still persisted as a process after the application was closed. In order to fix this, I registered the close event and kept track of the existence of the thread - i.e. basically, ignored the closeEvent until the thread was deleted as well.

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (workerThreadExists) {
        // Gracefully exiting all tasks inside the worker thread
        while (workerThreadExists){
            event->ignore();
        }
        event->accept();

    }
}

...and for me workerThreadExists is just a BOOLEAN that is set to true once the thread is created and then it is set to false when the thread is deleted. Hope this helps!




回答3:


You should have something like this:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    TabWindow w;
    w.show();
    return a.exec();
}

// Do quit in your TabWindow:
TabWindow::TabWindow()
  : public QWidget(NULL)
{
  connect( ui->myQuitButton, SIGNAL( clicked() ), qApp, SLOT( quit() ) );
}



回答4:


just replace

return a.exec();

with

return 0;

That should end all processes which is associated with that program.



来源:https://stackoverflow.com/questions/26181486/c-application-does-not-kill-all-processes-on-exit

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