c++ Qt Service未进入事件循环问题

fivyi3re  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(242)

我使用了旧的QtService代码:https://github.com/qtproject/qt-solutions/tree/master/qtservice并创建了一个服务来运行npm start命令,该命令将在Windows启动时启动我的网站。当添加-exec参数时,在app模式下启动它运行得很好,但当它作为服务运行时,它什么也不做。在调试过程中,我发现它没有正确地进入服务事件循环。因此,我创建了一个小示例,它应该将一些文本写入txt文件来说明这个问题。

代码:

  • 保险服务.h*
#ifndef INSURANCESERVICE_H
#define INSURANCESERVICE_H

#include <QCoreApplication>
#include <QObject>
#include <QThread>
#include <QDebug>
#include "qtservice.h"
#include "servicelogger.h"

class InsuranceService : public QtService<QCoreApplication>
{
    Q_GADGET
public:
    InsuranceService(int argc, char *argv[]);
    ~InsuranceService();

private:
    void start();
    void stop();
    void pause();
    void resume();
    void processCommand(int code);
    void createApplication(int &argc, char *argv[]);
};

#endif // INSURANCESERVICE_H
  • 保险服务.cpp*
#include "insuranceservice.h"

InsuranceService::InsuranceService(int argc, char *argv[]) : QtService<QCoreApplication>(argc, argv, "InsuranceService")
{
    std::cout << serviceName().toStdString().c_str() << std::endl;
    setServiceDescription("Test service");
    setServiceFlags(QtServiceBase::CanBeSuspended);
    //setStartupType(QtServiceController::AutoStartup);
}

void InsuranceService::start()
{
    try {
        QCoreApplication *insuranceApp = application();
        QFile *logFile = new QFile(ServiceLogger::getLogPath(), insuranceApp); 
        logFile->open(QIODevice::WriteOnly | QIODevice::Append);
        ServiceLogger::writeLog(logFile, QString("Test...").toUtf8());
        logFile->close();
        logFile->deleteLater();
    } catch (...) {
        qCritical() << "Failed to start the service!!!";
    }
}

void InsuranceService::stop()
{

}

void InsuranceService::pause()
{

}

void InsuranceService::resume()
{

}

void InsuranceService::processCommand(int code)
{
    Q_UNUSED(code);
}

void InsuranceService::createApplication(int &argc, char *argv[])
{
    QtService::createApplication(argc, argv);
}

InsuranceService::~InsuranceService()
{

}

main.cpp

#include <QCoreApplication>
#include "insuranceservice.h"

int main(int argc, char *argv[])
{
    InsuranceService service(argc, argv);
    return service.exec();
}

如何正确进入服务事件循环?

更新时间:

我尝试使用内置的logMessage方法运行此服务:

void InsuranceService::start()
{
    logMessage("The start method executing....", QtServiceBase::Success, 0, 0);
    QFile *logFile = new QFile(ServiceLogger::getLogPath());
    logFile->open(QIODevice::WriteOnly | QIODevice::Append);
    ServiceLogger::writeLog(logFile, QString("Test...").toUtf8());
    logFile->close();
    logFile->deleteLater();
}

Event Viewer中,它报告:* start方法正在执行....*
但由于某些原因,logMessage()以下的所有内容都不会执行。应该创建的日志文件不存在。问题可能是logMessage()在一个示例上运行,而QFile在另一个示例上创建/运行。我需要以某种方式连接到正确的示例。
谢谢你。

gab6jxml

gab6jxml1#

好的。我已经正确地调试了应用程序,发现当应用程序是服务时,QProcessQStandardPaths::writableLocationqgetenv不工作。服务功能似乎有限。因此,我决定将我的应用程序设置为在操作系统启动时运行,而不是服务。现在,它运行良好。问题已解决。谢谢

相关问题