找回密码
 立即注册
收起左侧

QProcess 启用CMD.exe,实现交互执行多次读写操作(在Win7平..

2
回复
9713
查看
[复制链接]
累计签到:2 天
连续签到:1 天
来源: 2017-8-17 00:06:47 显示全部楼层 |阅读模式
4Qter豆
本帖最后由 aming80 于 2017-8-17 00:11 编辑

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

因项目要在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<QApplication.h>
#include<QWidget.h>
#include<QDialog.h>
#include<QTextcodec.h>
#include<QString.h>
#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<QObject.h>
#include<QWidget.h>
#include<QThread.h>
#include<QString.h>
#include<Qthread.h>

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 <QCoreApplication>
#include <QProcess>
#include <QDebug.h>
#include <QString>
#include <QTime>
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:elay_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<QApplication.h>
#include <QWidget>
//#include"arentProcess.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 <QProcess>
#include <QThread>
#include <QByteArray>
#include <QDebug>
#include <QTextCodec>

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()<<outData;
//    MUi->txtMain->setText(outData);
//}



附件: 您需要 登录 才可以下载或查看,没有帐号?立即注册
回复

使用道具 举报

累计签到:2 天
连续签到:1 天
2017-8-17 10:01:23 显示全部楼层
已经解决,void workthread::read_slot() 的while循环内没有进行有效判断 ,造成了阻塞,没有办法写值,
我已经改成如下,可以正常读写了:
void workthread::read_slot()
{     
     while(myChildProcess->canReadLine())
     {
         char output[1024];
         int ret = myChildProcess->readLine(output,1023);
         qDebug() << ret;
         qDebug() << output;

         QString tmpstr;
         tmpstr=output;
         emit senddata_sign((QString)tmpstr);
         qDebug() << tmpstr;
     }
}
回复

使用道具 举报

尚未签到

2018-4-2 21:31:01 显示全部楼层
有完整的ui文件和属性么?
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

公告
可以关注我们的微信公众号yafeilinux_friends获取最新动态,或者加入QQ会员群进行交流:190741849、186601429(已满) 我知道了