Qt Service无法进入事件循环问题排查与解决求助
QtService服务模式下无法进入事件循环及文件写入异常问题
我基于Qt Solutions仓库中的QtService旧代码开发了一个Windows服务,目标是系统启动时自动执行npm start命令启动网站。在添加-exec参数以应用模式启动时,功能运行正常,但切换到服务模式后完全没有反应。调试发现服务并未正确进入事件循环,因此编写了一段向TXT文件写入文本的示例代码来复现问题。
示例代码
insuranceservice.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
insuranceservice.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(); }
请问如何让服务正确进入事件循环?
更新内容
我尝试使用QtService内置的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(); }
在Windows事件查看器中可以看到日志信息:The start method executing....,但logMessage()之后的代码均未执行,预期生成的日志文件也不存在。怀疑logMessage和QFile操作运行在不同的应用实例中,需要连接到正确的实例,求解决办法。
内容的提问来源于stack exchange,提问作者Hunter91151
相关产品推荐
相关产品推荐

