QtService实现后台服务linux,windows

ma1.QtService下载使用

地址:https://github.com/qtproject/qt-solutions

windows项目添加文件

qtservice_p.h,qtservice.h,qtservice.cpp,qtservice_win.cpp文件。

linux项目添加文件

qtservice_p.h,qtservice.h,qtservice.cpp,qtservice_unix.cpp,qtunixserversocket.h,qtunixserversocket.cpp,qtunixsocket.h,qtunixsocket.cpp文件。

示例代码

myService.h

#pragma once
 
#include <QObject>
#include "../qtservice/src/qtservice.h"
class myService : public QtService<QCoreApplication>
{
public:
	myService(int argc, char **argv);
	~myService()override;
protected:
	void start()override;
	void stop()override;
	void pause()override {}
	void resume()override {}

};

myService.cpp

#include "myService.h"
#include <QDebug>
 
myService::myService(int argc, char **argv) : QtService<QCoreApplication>(argc, argv, "QtServiceDemo")
{
	setServiceDescription("QtService Demo");
	setServiceFlags(QtServiceBase::CanBeSuspended);
}
 
myService::~myService()
{
}
 
void myService::start()
{
	qDebug()<<"myService start";
}
 
void myService::stop()
{
    qDebug()<<"myService stop";
}

main.cpp 


#include "myService.h"
#include <QtWidgets/QApplication>
 
int main(int argc, char *argv[])
{

 
	myService service(argc, argv);
	return service.exec();
}

2.windows服务注册脚本

服务操作指令可以写进batch脚本,然后以管理员身份运行。
比如 你的 MyService.exe 在C盘根目录

1)启动服务 start.bat文件:

@echo ------------Install MyService Name begin--------------
@echo off
@sc create "MyService Name" binPath="%~dp0MyService.exe" 
@sc config "MyService Name" start=AUTO
@net start "MyService Name"
@echo off
@echo ------------Install MyService Name Success--------------


2)卸载服务 stop.bat文件:

@echo ------------uninstall MyService Name begin--------------
@net stop "MyService Name"
@sc delete "MyService Name"
@echo ------------uninstall MyService Name Success--------------

3.linux服务注册脚本

myService.service

#Systemd unit file for myService
[Unit]
Description= myService
After=syslog.target network.target

[Service]
Type=forking

ExecStart=/home/myService/StartUp.sh
ExecStop =/home/myServicet/ShutDown.sh

User=root
Group=root
RestartSec=10
Restart=always

[Install]
WantedBy=multi-user.target

 copy myService.service /etc/systemd/system

  systemctl daemon-reload

  systemctl start myService.service //启动服务

  systemctl stop myService.service //停止服务

上一篇:简单记录一下ubantu18.04初步使用opencv所遇到的问题


下一篇:请求头中的Cookie和Referer(学习笔记)