Qt教程之实现程序自动重启 守护进程运行

0 486
索鸟 2021-03-15
需要:0索币

    没有任何人敢保证自己写的程序没有任何BUG,尤其是在商业项目中,程序量越大,复杂度越高,出错的概率越大,尤其是现场环境千差万别,和当初本地电脑测试环境很可能不一样,有很多特殊情况没有考虑到,如果需要保证程序7*24小时运行,则需要想一些办法能够让程序死了能够活过来,在嵌入式linux上,大部分会采用看门狗的形式来处理,程序打开看门狗驱动后,定时喂狗,一旦超过规定的时间,则硬件软复位等。这种方式相对来说比较可靠,如果需要在普通PC机上运行怎办呢?本篇文章提供一个软件实现守护进程的办法,原理就是udp通信,单独写个守护进程程序,专门负责检测主程序是否存在,不存在则启动。主程序只需要启动live类监听端口,收到hello就回复ok就行。
为了使得兼容任意程序,特意提炼出来共性,增加了多种设置。
1:可设置检测的程序名称。
2:可设置udp通信端口。
3:可设置超时次数。
4:自动记录已重启次数。
5:自动记录最后一次重启时间。
6:是否需要重新刷新桌面。
7:可重置当前重启次数和最后重启时间。
8:自动隐藏的托盘运行或者后台运行。
9:提供界面设置程序名称已经开启和暂停服务。
代码下载 live.zip (64 K) 下载次数:482
 

守护进程核心代码:

  1. #pragma execution_character_set("utf-8")
  2. #include "frmmain.h"
  3. #include "ui_frmmain.h"
  4. #include "qtimer.h"
  5. #include "qudpsocket.h"
  6. #include "qsharedmemory.h"
  7. #include "qprocess.h"
  8. #include "qdatetime.h"
  9. #include "qapplication.h"
  10. #include "qdesktopservices.h"
  11. #include "qmessagebox.h"
  12. #if (QT_VERSION > QT_VERSION_CHECK(5,0,0))
  13. #include "qstandardpaths.h"
  14. #endif
  15. #include "app.h"
  16. frmMain::frmMain(QWidget *parent) : QWidget(parent), ui(new Ui::frmMain)
  17. {
  18.     ui->setupUi(this);
  19.     this->initForm();
  20. }
  21. frmMain::~frmMain()
  22. {
  23.     delete ui;
  24. }
  25. void frmMain::changeEvent(QEvent *event)
  26. {
  27.     //隐藏当前界面,最小化到托盘
  28.     if(event->type() == QEvent::WindowStateChange) {
  29.         if(windowState() & Qt::WindowMinimized) {
  30.             hide();
  31.         }
  32.     }
  33.     QWidget::changeEvent(event);
  34. }
  35. void frmMain::initForm()
  36. {
  37.     count = 0;
  38.     ok = false;
  39.     //每秒钟定时询问心跳
  40.     timerHeart = new QTimer(this);
  41.     timerHeart->setInterval(2000);
  42.     connect(timerHeart, SIGNAL(timeout()), this, SLOT(sendHearData()));
  43.     //从6050端口开始,如果绑定失败则将端口加1,直到绑定成功
  44.     udp = new QUdpSocket(this);
  45.     int port = 6050;
  46.     while(!udp->bind(port)) {
  47.         port++;
  48.     }
  49.     connect(udp, SIGNAL(readyRead()), this, SLOT(readData()));
  50.     if (App::TargetAppName.isEmpty()) {
  51.         ui->btnStart->setText("启动");
  52.         ui->btnStart->setEnabled(false);
  53.         timerHeart->stop();
  54.     } else {
  55.         ui->btnStart->setText("暂停");
  56.         ui->btnStart->setEnabled(true);
  57.         timerHeart->start();
  58.     }
  59.     ui->txtAppName->setText(App::TargetAppName);
  60.     ui->txtAppName->setFocus();
  61. }
  62. void frmMain::sendHearData()
  63. {
  64.     udp->writeDatagram("hello", QHostAddress::LocalHost, App::TargetAppPort);
  65.     //判断当前是否没有回复
  66.     if (!ok) {
  67.         count++;
  68.     } else {
  69.         count = 0;
  70.         ok = false;
  71.     }
  72.     //如果超过规定次数没有收到心跳回复,则超时重启
  73.     if (count >= App::TimeoutCount) {
  74.         timerHeart->stop();
  75.         QSharedMemory mem(App::TargetAppName);
  76.         if (!mem.create(1)) {
  77.             killApp();
  78.         }
  79.         QTimer::singleShot(1000 , this, SLOT(killOther()));
  80.         QTimer::singleShot(3000 , this, SLOT(startApp()));
  81.         QTimer::singleShot(4000 , this, SLOT(startExplorer()));
  82.     }
  83. }
  84. void frmMain::killApp()
  85. {
  86.     QProcess *p = new QProcess;
  87.     p->start(QString("taskkill /im %1.exe /f").arg(App::TargetAppName));
  88. }
  89. void frmMain::killOther()
  90. {
  91.     QProcess *p = new QProcess;
  92.     p->start(QString("taskkill /im %1.exe /f").arg("WerFault"));
  93.     //重建缓存,彻底清除托盘图标
  94.     if (App::ReStartExplorer) {
  95.         QProcess *p1 = new QProcess;
  96.         p1->start("taskkill /f /im explorer.exe");
  97.     }
  98. }
  99. void frmMain::startApp()
  100. {
  101.     if (ui->btnStart->text() == "开始" || ui->btnStart->text() == "启动") {
  102.         count = 0;
  103.         return;
  104.     }
  105.     QProcess *p = new QProcess;
  106.     p->start(QString("\"%1/%2.exe\"").arg(qApp->applicationDirPath()).arg(App::TargetAppName));
  107.     count = 0;
  108.     ok = true;
  109.     timerHeart->start();
  110.     App::ReStartCount++;
  111.     App::ReStartLastTime = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
  112.     App::writeConfig();
  113.     ui->labCount->setText(QString("已重启 %1 次").arg(App::ReStartCount));
  114.     ui->labInfo->setText(QString("最后一次重启在 %1").arg(App::ReStartLastTime));
  115. }
  116. void frmMain::startExplorer()
  117. {
  118.     //取得操作系统目录路径,指定操作系统目录下的explorer程序,采用绝对路径,否则在64位操作系统下无效
  119. #if (QT_VERSION > QT_VERSION_CHECK(5,0,0))
  120.     QString str = QStandardPaths::writableLocation(QStandardPaths::ApplicationsLocation);
  121. #else
  122.     QString str = QDesktopServices::storageLocation(QDesktopServices::ApplicationsLocation);
  123. #endif
  124.     if (App::ReStartExplorer) {
  125.         str = QString("%1\\Windows\\explorer.exe").arg(str.mid(0, 2));
  126.         QProcess *p = new QProcess(this);
  127.         p->start(str);
  128.     }
  129. }
  130. void frmMain::readData()
  131. {
  132.     QByteArray tempData;
  133.     do {
  134.         tempData.resize(udp->pendingDatagramSize());
  135.         udp->readDatagram(tempData.data(), tempData.size());
  136.         QString data = QLatin1String(tempData);
  137.         if (data.right(2) == "OK") {
  138.             count = 0;
  139.             ok = true;
  140.         }
  141.     } while (udp->hasPendingDatagrams());
  142. }
  143. void frmMain::on_btnOk_clicked()
  144. {
  145.     App::TargetAppName = ui->txtAppName->text();
  146.     if (App::TargetAppName == "") {
  147.         QMessageBox::critical(this, "提示", "应用程序名称不能为空!");
  148.         ui->txtAppName->setFocus();
  149.         return;
  150.     }
  151.     App::writeConfig();
  152.     ui->btnStart->setEnabled(true);
  153. }
  154. void frmMain::on_btnStart_clicked()
  155. {
  156.     count = 0;
  157.     if (ui->btnStart->text() == "暂停") {
  158.         timerHeart->stop();
  159.         ui->btnStart->setText("开始");
  160.     } else {
  161.         timerHeart->start();
  162.         ui->btnStart->setText("暂停");
  163.     }
  164. }
  165. void frmMain::on_btnReset_clicked()
  166. {
  167.     App::ReStartCount = 0;
  168.     App::ReStartLastTime = "2019-01-01 12:00:00";
  169.     App::writeConfig();
  170.     ui->txtAppName->setText(App::TargetAppName);
  171.     ui->labCount->setText(QString("已重启 %1 次").arg(App::ReStartCount));
  172.     ui->labInfo->setText(QString("最后一次重启在 %1").arg(App::ReStartLastTime));
  173.     QMessageBox::information(this, "提示", "重置配置文件成功!");
  174. }

主程序使用核心代码:

  1. #include "applive.h"
  2. #include "qmutex.h"
  3. #include "qudpsocket.h"
  4. #include "qstringlist.h"
  5. #include "qapplication.h"
  6. #include "qdatetime.h"
  7. #include "qdebug.h"
  8. #define TIMEMS qPrintable(QTime::currentTime().toString("HH:mm:ss zzz"))
  9. QScopedPointer<AppLive> AppLive::self;
  10. AppLive *AppLive::Instance()
  11. {
  12.     if (self.isNull()) {
  13.         QMutex mutex;
  14.         QMutexLocker locker(&mutex);
  15.         if (self.isNull()) {
  16.             self.reset(new AppLive);
  17.         }
  18.     }
  19.     return self.data();
  20. }
  21. AppLive::AppLive(QObject *parent) : QObject(parent)
  22. {
  23.     udpServer  = new QUdpSocket(this);
  24.     QString name = qApp->applicationFilePath();
  25.     QStringList list = name.split("/");
  26.     appName = list.at(list.count() - 1).split(".").at(0);
  27. }
  28. void AppLive::readData()
  29. {
  30.     QByteArray tempData;
  31.     do {
  32.         tempData.resize(udpServer->pendingDatagramSize());
  33.         QHostAddress sender;
  34.         quint16 senderPort;
  35.         udpServer->readDatagram(tempData.data(), tempData.size(), &sender, &senderPort);
  36.         QString data = QLatin1String(tempData);
  37.         if (data == "hello") {
  38.             udpServer->writeDatagram(QString("%1OK").arg(appName).toLatin1(), sender, senderPort);
  39.         }
  40.     } while (udpServer->hasPendingDatagrams());
  41. }
  42. bool AppLive::start(int port)
  43. {
  44.     bool ok = udpServer->bind(port);
  45.     if (ok) {
  46.         connect(udpServer, SIGNAL(readyRead()), this, SLOT(readData()));
  47.         qDebug() << TIMEMS << "Start AppLive Ok";
  48.     }
  49.     return ok;
  50. }
  51. void AppLive::stop()
  52. {
  53.     udpServer->abort();
  54.     disconnect(udpServer, SIGNAL(readyRead()), this, SLOT(readData()));

  1. }

  1. 原文地址:http://www.qtcn.org/bbs/read-htm-tid-85364-ds-1.html

回帖
  • 消灭零回复
相关主题
2020年最新最新Kubernetes视频教程(K8s)教程 2
程序员转型之制作网课变现,月入过万告别996 1
索鸟快传2.0发布啦 1
两个不同网络的电脑怎么实现文件的互相访问呢? 1
网盘多账号登录软件 1
Java实战闲云旅游项目基于vue+element-ui 1
单点登录技术解决方案基于OAuth2.0的网关鉴权RSA算法生成令牌 1
QT5获取剪贴板上文本信息QT设置剪贴板内容 1
springboot2实战在线购物系统电商系统 1
python web实战之爱家租房项目 1
windows COM实用入门教程 1
C++游戏开发之C++实现的水果忍者游戏 1
计算机视觉库opencv教程 1
node.js实战图书管理系统express框架实现 1
C++实战教程之远程桌面远程控制实战 1
相关主题
PHP7报A non well formed numeric value encountered 0
Linux系统下关闭mongodb的几种命令分享 0
mongodb删除数据、删除集合、删除数据库的命令 0
Git&Github极速入门与攻坚实战课程 0
python爬虫教程使用Django和scrapy实现 0
libnetsnmpmibs.so.31: cannot open shared object file 0
数据结构和算法视频教程 0
redis的hash结构怎么删除数据呢? 0
C++和LUA解析器的数据交互实战视频 0
mongodb errmsg" : "too many users are authenticated 0
C++基础入门视频教程 0
用30个小时精通C++视频教程可能吗? 0
C++分布式多线程游戏服务器开发视频教程socket tcp boost库 0
C++培训教程就业班教程 0
layui的util工具格式时间戳为字符串 0
C++实战教程之远程桌面远程控制实战 1
网络安全培训视频教程 0
LINUX_C++软件工程师视频教程高级项目实战 0
C++高级数据结构与算法视频教程 0
跨域问题很头疼?通过配置nginx轻松解决ajax跨域问题 0