使用Windows中另一个进程的事件循环向Qt应用程序发送退出消息

Send a Quit message to Qt app with event loop from another process in Windows

本文关键字:应用程序 Qt 消息 退出 循环 Windows 另一个 进程 事件 使用      更新时间:2023-10-16

我用Qt和QTcpServer创建了一个服务器。它在后台运行,不显示任何窗口,但它使用事件循环。

我的主.cpp看起来像这样:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MyServer theServer;
    return a.exec();
}

如何在不诉诸TerminateProcess()的情况下通知我的服务器关闭?我对仅限Windows的解决方案很好,因此如果需要,我可以使用WINAPI功能。

根据服务器的用途,当您使用 TCPServer 时,您可以向它发送一条消息以告知它退出,尽管您可能希望验证谁在发送该消息。

或者,在同一台计算机上有一个控制器应用程序,该应用程序可以通过命名管道与服务器通信,您可以使用命名管道告诉它退出。

我只是使用 QLocalServer 实现它。事实证明,这很容易:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    static const char *quitSignalName = "My Service Quit Signal";
    const QStringList &args = a.arguments();
    if (args.size() == 2 && args[1] == "--shutdown") {
        // Connect to the named pipe to notify the service it needs
        // to quit. The QLocalServer will then end the event loop.
        QLocalSocket quitSignal;
        quitSignal.connectToServer(quitSignalName);
        quitSignal.waitForConnected();
        return 0;
    }
    // Listen for a quit signal, we connect the newConnection() signal
    // directly to QApplication::quit().
    QLocalServer quitSignalWatcher;
    QObject::connect(&quitSignalWatcher, SIGNAL(newConnection()), &a, SLOT(quit()));
    quitSignalWatcher.listen(quitSignalName);
    MyServer theServer;
    Q_UNUSED(theServer);
    return a.exec();
}