-1

我已经使用 Qt 和QTcpServer. 它在后台运行并且不显示任何窗口,但它使用事件循环。

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

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

我如何通知我的服务器关闭,而不诉诸于TerminateProcess()?我可以使用仅限 Windows 的解决方案,因此如果需要,我可以使用 WINAPI 函数。

4

2 回答 2

2

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

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

于 2013-11-12T15:23:56.087 回答
2

我刚刚使用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();
}
于 2013-11-12T17:48:53.760 回答