前言
Qprocess作为Qt的进程通信类,在程序中的应用还是挺多的,不管是启动一个命令行,还是另外启动一个辅助程序,QProcess都是不可或缺的。
之前也遇到过类似场景,主进程开始一个辅助进程执行Python脚本,需要传递函数名和参数,并且接受执行结果,那会是用的共享内存做的,当时是单向,主进程在共享内存段写入函数名和参数,副进程定时读取,有滞后。反正需求是实现了,当时也没想那么多。。。
最近有时间,专门研究了下QProcess,双向通信是可行的。当然我这边环境是基于windows的,Qt5.9+msvc2017 x64,系统是win10
一、QProceess简介
关于QProcess的介绍我就不多说了,相信大家都很了解了,不是很了解的可以查看Qt文档。我这里主要说下几个信号:
void readyReadStandardError()
void readyReadStandardOutput()
这两个对应的就是stdout和stderr,即副进程的标准输出和标准错误通道有可读内容是,这两个信号会发出来,主进程只要绑定这两个槽函数进行相应处理就行了。
QByteArray QProcess::readAllStandardError()
QByteArray QProcess::readAllStandardOutput()
这两个就是上面绑定的槽函数里面,读取对应的内容
二、实例
1.进程A(主进程)
代码如下(示例):
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow),mProcess(new QProcess)
{
ui->setupUi(this);
setWindowTitle("processServer");
init_Process();
}
MainWindow::~MainWindow()
{
delete ui;
if(mProcess){
mProcess->close();
delete mProcess;
}
}
void MainWindow::init_Process()
{
connect(mProcess,&QProcess::readyReadStandardOutput,this,&MainWindow::slot_readyStandandOutput);
connect(mProcess,&QProcess::readyReadStandardError,this,[=](){
QString log = mProcess->readAllStandardError();
print_log(0,log);
});
QStringList argunments;
argunments <<"123456";
mProcess->start("F:/QtProject/build-processClient-Desktop_Qt_5_9_9_MSVC2017_64bit-Release/release/processClient.exe",argunments);
if(mProcess->waitForStarted(3))
{
qDebug()<<"进程启动成功";
}else{
qDebug()<<"进程启动失败!";
}
}
void MainWindow::print_log(quint8 t, QString &log)
{
if(t){
log="[标准输出]:"+log;
ui->plainTextEdit->appendHtml("<font color=\"#000000\">" + log + "</font> ");
}else{
log="[标准错误]:"+log;
ui->plainTextEdit->appendHtml("<font color=\"#FF0000\">" + log + "</font> ");
}
}
void MainWindow::slot_readyStandandOutput()
{
QString log = mProcess->readAllStandardOutput();
print_log(1,log);
}
void MainWindow::on_pushButton_clicked()
{
QString text = ui->lineEdit->text();
if(text.isEmpty()) return;
if(mProcess){
mProcess->write(text.toStdString().c_str());
}
}
demo中构造函数里面进行初始化,开启副进程,路径记得换下你自己的路径,参数的话,传不传都行,根据自己需要。
2.进程B
代码如下(示例):
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <QFuture>
#include <QtConcurrent/QtConcurrent>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow),mFileIN(new QFile)
{
ui->setupUi(this);
setWindowTitle("processClient");
#if 0
QTimer::singleShot(5000, this,[=](){initFileIN();});
#else
QFuture<void> f1 = QtConcurrent::run(this,&MainWindow::readstdin);
connect(this,&MainWindow::sig_receivedCommand,this,[&](QString text){
ui->textEdit->append("[读取标准输入]"+ text);
});
connect(this,&MainWindow::sig_log,this,&MainWindow::slot_print);
#endif
}
MainWindow::~MainWindow()
{
delete ui;
if(mFileIN){
mFileIN->close();
delete mFileIN;
}
}
void MainWindow::on_pushButton_clicked()
{
QString text = ui->lineEdit->text();
if(text.isEmpty()) return;
#if 0
QFile fileout;
if(fileout.open(stdout,QIODevice::WriteOnly)){
fileout.write(text.toStdString().c_str());
}else{
printErr("open fail");
}
fileout.close();
#else
std::cout<<text.toStdString()<<std::endl;
#endif
}
void MainWindow::printErr(const QString &errText)
{
QFile fileerr;
if(fileerr.open(stderr,QIODevice::WriteOnly)){
fileerr.write(errText.toStdString().c_str());
}
fileerr.close();
}
void MainWindow::on_pushButton_2_clicked()
{
QString text = ui->lineEdit->text();
if(text.isEmpty()) return;
#if 0
QFile fileerr;
if(fileerr.open(stderr,QIODevice::WriteOnly)){
fileerr.write(text.toStdString().c_str());
}
fileerr.close();
#else
std::cerr<<text.toStdString()<<std::endl;
#endif
}
void MainWindow::slot_print(const QString &text)
{
qDebug()<<text;
ui->textEdit->append("[读取标准输入]"+ text);
}
void MainWindow::readstdin()
{
bool ok = true;
char chBuf[4096];
DWORD dwRead;
HANDLE hStdinDup;
const HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
if (hStdin == INVALID_HANDLE_VALUE)
return;
DuplicateHandle(GetCurrentProcess(), hStdin,
GetCurrentProcess(), &hStdinDup,
0, false, DUPLICATE_SAME_ACCESS);
CloseHandle(hStdin);
while (ok) {
ok = ReadFile(hStdinDup, chBuf, sizeof(chBuf), &dwRead, NULL);
emit sig_log(QLatin1String("ok is:")+QString::number(ok));
if (ok && dwRead != 0) emit sig_receivedCommand(QString::fromUtf8(chBuf, dwRead));
}
}
构造函数中开了个Qtconcuurrent高级线程接口,运行readstdin函数,函数中有涉及到while阻塞,一直检测标准输入通道stdin是否有可读取的信息,因此另开线程。
3.运行
demo下载
https://download.csdn.net/download/weixin_46424582/86412084
总结
例如:以上就是今天要讲的内容,具体可查看demo,仅仅演示了Qprocess的双向通信,实际应用场景还未验证。