QProcess 启用CMD.exe,实现交互多次执行读写指令(在Win7平台) 2C

因项目要在Windows下开启CMD程序,通过与CMD程序交互进行读写,
举例:开启CMD程序 按顺序执行如下指令,每执行一条指令后,并读取CMD的反馈信息,再执行下一条指令,再读取CMD反馈信息,当指令全部都执行完毕后,再关闭CMD程序;
0.cd f:\test(进入f:\test\目录);
1.dir(查看当前目录文件);
2.ver (查看系统版本);
3.ipconfig(查看IP地址);
4.time (查看当前时间);
5.ping 192.168.1.1 -n 10 (Ping路由器地址);
6.iperf -s (执行iperf指令);

备注:把读CMD输出信息动作放至到while中让它循环读取CMD的输出信息,写一条读一条,就像串口通信一样;

目前状态是:通过QProcess启动CMD,可以读出CMD启动时输出的信息,但后面再调用进程调用wirte(QString *)给CMD下指令,wirte执行完成后,CMD没有任何反馈?

在论坛上找了好久没有和我用法相同的情况,CSDN博客"一去二三里"也没有,请问那路前辈,大侠,谁这样弄过,我该要如何写? 第一次用QT,麻烦大家了。

如下是我的代码:

#include
#include
#include
#include
#include
#include "MainWindow.h"

int main(int argc, char*argv[])
{
QApplication a(argc,argv);
QTextCodec *codec = QTextCodec::codecForName("GBK");
QTextCodec::setCodecForTr(codec);
QTextCodec::setCodecForLocale(QTextCodec::codecForLocale());
QTextCodec::setCodecForCStrings(QTextCodec::codecForLocale());

MainWindow w;
w.show();
return a.exec();

}

//------------------------------------------workthread.h file------------------------------------------

#ifndef WORKTHREAD_H
#define WORKTHREAD_H

#include
#include
#include
#include
#include

class QProcess;

class workthread:public QObject
{
Q_OBJECT

public:
    explicit workthread( QObject *param=0);
     ~workthread();

   bool b_loopread;

public:
   QProcess* myChildProcess;


public slots:
    void read_slot();
    void write_slot(QString );
    void stopread_slot();
    void IniCmdThread_slot();

// void doWork(int parameter)
// {
// qDebug()<<"receive the execute signal---------------------------------";
// qDebug()<<" current thread ID:"<<QThread::currentThreadId();
// //寰幆涓€鐧句竾娆�
// for(int i = 0;i!=1000000;++i)
// {
// ++parameter;
// }
// //鍙戦€佺粨鏉熶俊鍙�
// qDebug()<<" finish the work and sent the resultReady signal\n";
// emit resultReady(parameter);
// }

  //绾跨▼瀹屾垚宸ヤ綔鏃跺彂閫佺殑淇″彿
  signals:
    void senddata_sign(QString);

private:
void Delay_MSec(unsigned int msec);
};

#endif // WORKTHREAD_H

//------------------------------------------workthread.cpp file------------------------------------------
#include"workthread.h"
#include
#include
#include
#include
#include
workthread::workthread(QObject *param):
QObject(param)
{
b_loopread=false;

}
workthread::~workthread()
{
myChildProcess->close();

delete myChildProcess;

myChildProcess=NULL;
qDebug() << "end myChildProcess " << "\r\n";

}

void workthread::IniCmdThread_slot()
{
qDebug() << "IniCmdThread_slot()";
myChildProcess = new QProcess(this);
myChildProcess->setProcessChannelMode(QProcess::MergedChannels);
QObject::connect(myChildProcess,SIGNAL(readyReadStandardOutput()),this,SLOT(read_slot()));
myChildProcess->start("CMD.exe");
if (!myChildProcess->waitForStarted())
qDebug() << "Make failed:" << myChildProcess->errorString();
else
{
// qDebug() << "Child Process Started.123 " << myChildProcess->readAll();
b_loopread=true;
}
}

void workthread::read_slot()
{
while(b_loopread)
{
Delay_MSec(1000);
// if(myChildProcess->waitForReadyRead())
// {
char output[128];
qint64 rec=myChildProcess->readLine(output,127);
if((strlen(output)!=0)&&(rec!=-1))
{
QString tmpstr;
tmpstr=output;
emit senddata_sign((QString)tmpstr);
qDebug() << tmpstr;
}
// }
}
}

void workthread::write_slot(QString strWrite)
{
char*ch;
QByteArray ba = strWrite.toLatin1();
ch=ba.data();
myChildProcess->write("dir\r");
myChildProcess->waitForBytesWritten(2000);

// if(myChildProcess->waitForBytesWritten())
// {
qDebug() <<"workthread::write_slot "<<strWrite;
// }
}

void workthread::stopread_slot()
{
b_loopread=false;
}

void workthread::Delay_MSec(unsigned int msec)
{
QTime _Timer = QTime::currentTime().addMSecs(msec);

while( QTime::currentTime() < _Timer )

QCoreApplication::processEvents(QEventLoop::AllEvents, 100);

}

//----------------------MainWindow.h---------------------------------

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include
#include
//#include"ParentProcess.h"
#include"workthread.h"

namespace Ui{
class MainWindow;
}

class MainWindow: public QWidget
{

Q_OBJECT
QThread workerThread;

public:
  explicit MainWindow(QWidget *param=0);
  ~MainWindow();


 signals:
    void IniCmdThread_sign();
    void read_sign();
    void write_sign(QString);
    void stopread_sign();
    void sendcomd_sign(QString);


 public slots:
    void SendCommand();
    void getdata_slot(QString);
    void stopRead();

 private:
    QString str_rece_total;
    Ui::MainWindow *MUi;

// ParentProcess* obj;

};

#endif // MAINWINDOW_H

//----------------------MainWindow.cpp---------------------------------

#include"MainWindow.h"
#include"ui_MainWindow.h"
#include
#include
#include
#include
#include

MainWindow::MainWindow(QWidget* param):
QWidget(param),
MUi(new Ui::MainWindow)
{

MUi->setupUi(this);
workthread *work=new workthread;
work->moveToThread(&workerThread);
// QTextCodec::setCodecForTr=QTextCodec::codeForName("UTF-8");

//IniCmdThread_sign淇″彿鍙戝皠鍚�,鍚姩绾跨▼鍒濆鍖朇MD杩涚▼;
connect(this, SIGNAL(IniCmdThread_sign()), work, SLOT(IniCmdThread_slot()));

//璇ョ嚎绋嬬粨鏉熸椂閿€姣�

// connect(&workerThread,SIGNAL(&QThread::finished()), work,SLOT(&QObject::deleteLater()));

connect(this, SIGNAL(write_sign(QString)), work, SLOT(write_slot(QString)));
connect(this, SIGNAL(read_sign()), work, SLOT(read_slot()));
connect(MUi->btnStop,SIGNAL(clicked()), this, SLOT(stopRead()));
connect(this, SIGNAL(stopread_sign()), work, SLOT(stopread_slot()));

connect(work,SIGNAL(senddata_sign(QString)),this,SLOT(getdata_slot(QString)));
connect(this,SIGNAL(sendcomd_sign(QString)),work,SLOT(write_slot(QString)));
connect(MUi->btnSend,SIGNAL(clicked()),this,SLOT(SendCommand()));
//鍚姩绾跨▼
workerThread.start();

//鍙戝皠淇″彿锛岃皟鐢ㄥ瓙绾跨▼涓繘绋嬧€淐MD.exe鈥�;
qDebug()<<"current Main thread ID:"<<QThread::currentThreadId()<<'\n';
emit IniCmdThread_sign();

//鍙戝皠淇″彿锛屽紑濮嬪惊鐜墽琛岋紝璇诲彇杩涚▼鈥淐MD.exe鈥濈殑杩斿洖淇℃伅;
emit read_sign();

}

MainWindow::~MainWindow()
{
emit sendcomd_sign("exit\r\n");
workerThread.quit();
workerThread.wait();
delete MUi;
}

void MainWindow::getdata_slot(QString info)
{
QString str_info="Recevie:";
str_info.append(info);
str_info.append("\n");
str_rece_total.prepend(str_info);

MUi->txtMain->setText(str_rece_total);

}

void MainWindow::SendCommand()
{
QString str_comd=MUi->txtEditComd->toPlainText();
str_comd+='\r';
emit sendcomd_sign(str_comd);
}

void MainWindow::stopRead()
{
emit stopread_sign();
}

//void MainWindow::RunTest()
//{
// qDebug() << "1235477777";

// qDebug()<<"Read";
// QString outData = obj->myChildProcess->readAllStandardOutput();
// qDebug()< // MUi->txtMain->setText(outData);
//}
图片说明

1个回答

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问