Qt 服务程序
了解服务
删除服务
#删除服务
sc delete MySQL
Qt 官方源码和例子
https://github.com/qtproject/qt-solutions/blob/master/qtservice/examples/interactive/main.cpp
直接下载编译即可
#include <QCoreApplication>
#include "qtservice.h"
#include <QDebug>
#include <QProcess>
#include <QDir>
class InteractiveService : public QtService<QCoreApplication>
{
public:
InteractiveService(int argc, char **argv);
~InteractiveService();
void start() override;
private:
};
InteractiveService::InteractiveService(int argc, char **argv)
: QtService<QCoreApplication>(argc, argv, "QtRobodService")
{
setServiceDescription("A robod service with user interface.");
setServiceFlags(QtServiceBase::CanBeSuspended);
}
InteractiveService::~InteractiveService()
{
}
void InteractiveService::start()
{
if(this->application()){
QString appDirPath = this->application()->applicationDirPath();
QString str = appDirPath.replace("\\","/");
// // qDebug()<<"str:"<<str;
// {
// auto list = str.split("/");
// list.takeLast();
// str = list.join("/");
// }
// // qDebug()<<"str:"<<str;
str = str+"/startUp.bat";
bool isOK = QProcess::startDetached(QString("cmd /c start %1").arg(str));
if(!isOK){
str += "\n";
str = str +" startDetached failed";
}
{
QFile file(appDirPath+"/1.txt");
file.open(QIODevice::WriteOnly);
file.write(str.toLocal8Bit());
file.close();
}
}
#if defined(Q_OS_WIN)
if ((QSysInfo::WindowsVersion & QSysInfo::WV_NT_based) &&
(QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA)) {
logMessage( "Service GUI not allowed on Windows Vista. See the documentation for this example for more information.", QtServiceBase::Error );
return;
}
#endif
}
int main(int argc, char *argv[])
{
#if !defined(Q_OS_WIN)
// QtService stores service settings in SystemScope, which normally require root privileges.
// To allow testing this example as non-root, we change the directory of the SystemScope settings file.
QSettings::setPath(QSettings::NativeFormat, QSettings::SystemScope, QDir::tempPath());
qWarning("(Example uses dummy settings file: %s/QtSoftware.conf)", QDir::tempPath().toLatin1().constData());
#endif
InteractiveService service(argc, argv);
// xxx.exe -i (xxx.exe -install)安装的一个当前用户帐号的服务。
// xxx.exe -s 表示启动了这个Service. 此时,在系统的Service查看窗口按F5刷新,可以看到这个服务的运行状态已经变成Running了。
// xxx.exe -p (xxx.exe -pause)暂停这个服务
// xxx.exe -r (xxx.exe -resume)继续这个服务
// xxx.exe -t (xxx.exe -terminate)停止这个服务
// xxx.exe -v(xxx.exe -version)
// xxx.exe -c (xxx.exe -command )
// xxx.exe -h(xxx.exe -help)帮助
// xxx.exe -u (xxx.exe -uninstall)卸载这个服务。
//安装服务,管理员权限 cmd WinSystemServer.exe -i
return service.exec();
}
启动服务脚本 autoStart.bat
@echo off
set path=%~dp0
start %path%/WinSystemServer.exe -i
start net start QtRobodService
exit
停止并删除服务脚本 autoStop.bat
@echo off
start net stop QtRobodService
start sc delete QtRobodService
exit
服务启动.exe脚本 (这里只在服务器启动后启动一次)
startUp.bat
@echo off
cd %~dp0
cd ..
set path=%cd%
@echo %path%
start %path%/robod/RobodPro.exe
exit