前言
测试实现监视指定名称的软件是否在运行,如果没有运行则像指定的IP发送监测结果。
提示:以下是本篇文章正文内容,下面案例可供参考
1.pro文件
QT += core gui concurrent network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++11
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h
FORMS += \
mainwindow.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
2.MainWindow.h
代码如下(示例):
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QProcess>
#include <QTimer>
#include <QDebug>
#include <QtConcurrentRun>
#include <QDragEnterEvent>
#include <QUrl>
#include <QFile>
#include <QMimeData>
#include <QTcpSocket>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void inItData();
void WhetherProcessRunning();
void IsRunning();
void TCP_Receive_Data(); //接收板卡发送回来的TCP数据
void slotdisconnected(); //与服务器端口连接处理函数
void Connect_TCP_Server();
void sendData(QString info);
signals:
void send_statue(QString runStatue = "");
private slots:
void getAppRunStatue(QString runStatue);
void TCP_SerialPort_Status();
private:
Ui::MainWindow *ui;
QTimer monitorTimer;
QString appName;
bool statue;
QTcpSocket TCP_clientSocket; //TCP套接字
QTimer Serial_port_status_timer;
int TCP_Reconnection_times = 0;
QString appStatue;
private:
void dragEnterEvent(QDragEnterEvent *event);
void dropEvent(QDropEvent *event);
void closeEvent(QCloseEvent *event);
};
#endif // MAINWINDOW_H
3.MainWindow.cpp
代码如下(示例):文章来源:https://www.toymoban.com/news/detail-799370.html
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDir>
#include <QThread>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
inItData();
Connect_TCP_Server();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::inItData()
{
setAcceptDrops(true);
//初始化TCP对象
connect(&TCP_clientSocket,&QTcpSocket::readyRead, this, &MainWindow::TCP_Receive_Data); //读到TCP服务器传来的信号
connect(&TCP_clientSocket, &QTcpSocket::disconnected, this, &MainWindow::slotdisconnected);
connect(&monitorTimer, &QTimer::timeout, this, &MainWindow::IsRunning);
connect(this, &MainWindow::send_statue, this, &MainWindow::getAppRunStatue);
connect(&Serial_port_status_timer,&QTimer::timeout,this,&MainWindow::TCP_SerialPort_Status);//实时更新端口号
IsRunning();
monitorTimer.start(1000);
}
void MainWindow::WhetherProcessRunning()
{
QProcess process;
QString cmd = "tasklist";
process.start(cmd);
process.waitForFinished(); //等待进程结束
QString str = process.readAllStandardOutput();//获取执行命令后的输出内容
if(str.contains(appName) && !appName.isEmpty())//判断是否有包含当前指定的进程名
{
appStatue = "运行中";
}
qDebug() << "子线程ID: " << QThread::currentThreadId();
emit send_statue();
}
void MainWindow::IsRunning()
{
appStatue = "未运行";
appName = ui->lineEdit->text().trimmed();
qDebug() << "主线程ID: " << QThread::currentThreadId();
QtConcurrent::run(this,&MainWindow::WhetherProcessRunning);
}
void MainWindow::getAppRunStatue(QString runStatue)
{
qDebug()<< "运行状态: " << appStatue;
ui->label_3->setText(appStatue);
if(appStatue == "运行中")
ui->label_3->setStyleSheet("font-size:24px; color: rgb(85, 170, 0);");
if(appStatue == "未运行" && TCP_clientSocket.isOpen())
{
ui->label_3->setStyleSheet("font-size:26px; color: rgb(237,28,36);");
sendData(QString("软件%1运行状态: %2").arg(appName).arg(appStatue));
}
}
//拖动进入事件
void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
//可打开.txt,.h,.cpp文件
if(event->mimeData()->hasUrls()) //数据中是否包含URL
{
event->acceptProposedAction(); //如果是则接受动作
}
else
event->ignore();
}
//放下事件
void MainWindow::dropEvent(QDropEvent *event)
{
const QMimeData *mimeData = event->mimeData();
if(mimeData && mimeData->hasUrls())
{
QList<QUrl>urlList = mimeData->urls();
QString fileName = urlList.at(0).toLocalFile();
qDebug()<< "fileName = " << fileName;
QString suffix = fileName.mid(fileName.lastIndexOf("/")+1,100);
qDebug()<< "suffix = " << suffix;
}
}
void MainWindow::closeEvent(QCloseEvent *event)
{
if(TCP_clientSocket.isOpen())
{
TCP_clientSocket.disconnect();
monitorTimer.stop();
Serial_port_status_timer.stop();
TCP_clientSocket.close();
}
QMainWindow::closeEvent(event);
}
void MainWindow::Connect_TCP_Server()
{
TCP_clientSocket.abort();
TCP_clientSocket.connectToHost("192.168.0.102", 4001);
if(!TCP_clientSocket.waitForConnected(3000))
{
qDebug()<< "连接失败!";
return;
}
}
//接收板卡发送回来的TCP数据
void MainWindow::TCP_Receive_Data()
{
//获取对方发送的内容
QByteArray info = TCP_clientSocket.readAll();
QString data = QString::fromUtf8(info);
qDebug()<< "data: " << data;
}
//与服务器端口连接处理函数
void MainWindow::slotdisconnected()
{
qDebug() << " 连接状态: 已断开(TCP)";
Serial_port_status_timer.start(3000); //连接断开时开启定时器,定时时间为3s
}
//向板卡发送数据
void MainWindow::sendData(QString info)
{
//通过TCP向板卡发送数据
QByteArray TCP_Data = info.toUtf8();
qDebug()<< "发送的消息的TCP数据 = " << TCP_Data << "info = " << info;
TCP_clientSocket.write(TCP_Data);
// bool statue = TCP_clientSocket.waitForReadyRead(1500);
// if( statue == false)
// {
// qDebug()<< "无数据返回!";
// return;
// }
}
void MainWindow::TCP_SerialPort_Status()
{
QString StatusBarMessage;
if(TCP_Reconnection_times == 10)
{
TCP_Reconnection_times = 0;
Serial_port_status_timer.stop();
StatusBarMessage = tr(" 设备重连失败!");
qDebug()<< StatusBarMessage;
ui->statusbar->setStyleSheet("font-size:18px; color: rgb(237,28,36);");
ui->statusbar->showMessage(StatusBarMessage);
return;
}
TCP_clientSocket.abort();
TCP_clientSocket.connectToHost("192.168.0.102", 4001);
ui->statusbar->setStyleSheet("font-size:18px; color: rgb(237,28,36);");
StatusBarMessage = tr(" 正在重新连接...");
qDebug()<< StatusBarMessage;
ui->statusbar->showMessage(StatusBarMessage);
if(!TCP_clientSocket.waitForConnected(1500))
{
TCP_Reconnection_times++; //没重连一次失败次数加一,重连失败10次后停止重连
ui->statusbar->setStyleSheet("font-size:18px; color: rgb(237,28,36);");
StatusBarMessage = QString(tr(" 请求超时,连接失败!(重连次数: %1 )")).arg(TCP_Reconnection_times);
qDebug()<< StatusBarMessage;
ui->statusbar->showMessage(StatusBarMessage);
return;
}
else
{
TCP_Reconnection_times = 0;
Serial_port_status_timer.stop();
ui->statusbar->setStyleSheet("font-size:18px; color: rgb(85, 170, 0);");
StatusBarMessage = tr(" 连接状态: 已连接(TCP)");
qDebug()<< StatusBarMessage;
ui->statusbar->showMessage(StatusBarMessage);
}
}
4.效果演示
文章来源地址https://www.toymoban.com/news/detail-799370.html
到了这里,关于【QT】使用QtConcurrent实时监测指定软件的运行状态的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!