QT实现后台服务,linux下使用systemd管理QT后台服务

本文详细介绍了如何使用QtService在Ubuntu上实现后台服务,并结合systemd进行服务管理。通过QT创建服务,利用systemctl命令进行服务的启动、停止、重启和状态检查。此外,还讲解了systemd的unit配置文件和常用命令,以及如何创建和管理systemd服务单元。最后,展示了服务的测试效果和可能出现的问题。

1、用法:systemctl [OPT] COMMAND [NAME]…

启动服务:systemctl start name.service

停止服务:systemctl stop name.service

重启服务:systemctl restart name.service

服务状态:systemctl status name.service

服务重载:systemctl daemon-reload

条件式重启,已启动才重启,否则不作操作:systemctl try­restart name.service

重载或重启服务,先加载再启动:systemctl reload­or­restart name.service

重载或条件式重启:systemctl reload­or­try­restart name.service

禁止自动和手动启动:systemctl mask name.service

取消禁止:systemctl unmask name.service

查看某服务当前激活与否的状态:systemctl is­active name.service

查看所有已经激活的服务:systemctl list­units ­t service

查看所有服务:systemctl list­units ­t service ­a

设定某服务开机自启动:systemctl enable name.service

设定某服务开机禁止启动:systemctl disable name.service

查看所有服务的开机自启动状态:systemctl list­unit­files –t service

列出该服务在哪些运行级别下启用和禁止:ls /etc/systemd/system/*.wants/sshd.service

查看服务是否开机启动:systemctl is­enabled name.service

查看服务的依赖关系:systemctl list­dependencies name.service

杀掉进程:systemctl kill (进程名)

2、服务状态:

loaded:unit配置文件已处理

active(running):一次或多次持续处理的运行

active(exited):成功完成一次性配置

active(waiting):运行中,等待一个事件

inactive:不运行

enable:开机启动

disable:开机不启动

static:开机不启动,但可以被另一个启用的服务激活。

一、QT实现后台服务
QT使用开源项目QtService实现后台服务,支持windows和linux跨平台使用,下载地址:
https://github.com/qtproject/qt-solutions/tree/master/qtservice

QT新建控制台程序"Qt Console Application",把qtservice文件夹拷贝到QT工程目录,在pro文件添加:

include(qtservice/src/qtservice.pri)
1
添加新文件:ubuntuservice.h和ubuntuservice.cpp,服务功能主要由重写的几个虚函数完成:start、stop、pause、resume,在启动、停止、暂停、重启服务时会自动调用这些虚函数。
下面的demo用QProcess启动停止外部程序,功能在外部程序实现(test_systemd),这里外部程序的功能是启动一个TCP客户端,连接到服务器,当收到服务器的消息时自动回复一条confirm消息。
修改main.cpp

#include "ubuntuservice.h"
int main(int argc, char *argv[])
{
    ubuntuService service(argc, argv);
    return service.exec();
}
1
2
3
4
5
6
ubuntuservice.h

#ifndef UBUNTUSERVICE_H
#define UBUNTUSERVICE_H

#include <QCoreApplication>
#include <QProcess>
#include "qtservice.h"

class ubuntuService : public QObject,public QtService<QCoreApplication>
{
    Q_OBJECT
public:
    ubuntuService(int argc, ch

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蝈蝈(GuoGuo)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值