What's the best way of implementation QProcess, which reading stdout and stderr in "real time"?

Go To StackoverFlow.com

0

This questions is often asked. Many recommend use readyReadStandardOutput for this purpose What's the best way of implementation QProcess, which reading stdout and stderr in "real time"? I want to add messages in DisplayEdit. What i must change in my code (you can see it below )? May be use QThread for writing in DisplayEdit? I've already the following code:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QProcess>
#include <QDebug>
#include <QCloseEvent>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    process = new QProcess(this);
    connect(process, SIGNAL(readyReadStandardOutput()),SLOT(slotDataOnStdout()));
    connect(process, SIGNAL(readyReadStandardError()), SLOT(slotProcessError()));
    connect(process, SIGNAL(error(QProcess::ProcessError)),SLOT(slotProcessError()));
    connect(process, SIGNAL(started()),SLOT(slotProcessStart()));
    connect(process, SIGNAL(finished(int)),SLOT(slotProcessFinish(int)));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_EnterButton_clicked()
{
    QStringList args = ui->ArgsEdit->text().split(" ");
    QString cmd = ui->CommandEdit->text();
    process->start(cmd, args);

}

void MainWindow::slotDataOnStdout()
{
    qDebug() << "slotDataOnStdout";
    ui->DisplayEdit->append(process->readAllStandardOutput() + '\n');
}

void MainWindow::slotStderr()
{
    qDebug() << "std error";
}

void MainWindow::slotProcessError()
{
    qDebug() << "error";
}

void MainWindow::slotProcessStart()
{
    qDebug() << "start";
}

void MainWindow::slotProcessFinish(int exitCode)
{
    qDebug() << "finish: " << exitCode;
    QString str = process->readAllStandardOutput();
    qDebug() << str;
}

And i want to execude the binary file of countdown timer. The code of my timer (i have took it from clock reference:

#include <stdio.h>
#include <time.h>

void wait ( int seconds )
{
  clock_t endwait;
  endwait = clock () + seconds * CLOCKS_PER_SEC ;
  while (clock() < endwait) {}
}

int main ()
{
  int n;
  printf ("Starting countdown...\n");
  for (n=10; n>0; n--)
  {
    printf ("%d\n",n);
    wait (1);
  }
  printf ("FIRE!!!\n");
  return 0;
}
2012-04-03 20:34
by G-71
It helps to keep your questions separate, if only because you cannot accept 2 answers here - MSalters 2012-04-03 20:42


1

Looks mostly right. You did forgot to clean up the process, or think about what to do when the process isn't finished yet.

As for the timer, use the QTimer::timeout signal.

2012-04-03 20:45
by MSalters
Ads