Home > Software engineering >  How to avoid getting mixed outputs with QProcess->readAllStandardOutput()?
How to avoid getting mixed outputs with QProcess->readAllStandardOutput()?

Time:12-16

I have a QProcess in which I get data from the backend of my application. I have a simple connection to get the output string generated by QProcess. Right now it works well if I request a single command.

Now, I need to run two commands in a row one by one. The expected behavior is the following:

  • Send command 1

  • Wait for the output of command 1

  • Store the output of command 1 in a variable

  • Send command 2

  • Wait for the output of command 2

  • Store the output of command 2 in a variable

But I'm having an unexpected behavior. The two commands are sent to the backend, but sometimes I get a mixed output from the two outputs. I think it could be related to the time it takes for the backend to return the first result. I need to wait for the first output to send the second command. Any ideas on how to solve this problem?

If if use study->waitForFinished(); or study->waitForFinished(-1); the app freezes and then crash.

This is my code:

connect(study, &QProcess::readyReadStandardOutput, [=] {
  QString out = study->readAllStandardOutput();
  qDebug()<< "Output= " << out;
}
void StudyClass::writeCommand(const QString& line) {
    study->write(line.toLocal8Bit());
}

If I write two commands as follows:

    writeCommand("print_status;");
    writeCommand("print_say_hello");

Sometimes I get the desired output (qDebug called in the connection):

    Output= 0
    Output= hello world

But sometimes I just get a mixed output:

    Output= 0 hello world

This is wrong behavior, because I need to get results for each command instead of just one.

CodePudding user response:

In order to have separate outputs for the two commands you have to wait for the first output and only then send the second command. You seem to send both commands without a delay and so occasionally you get the output of both commands in one call to the signal handler.

CodePudding user response:

If I understand correctly, your QProcess is a long running process taking input commands through stdin, and then you want to capture the output of each of these commands. If that is the case, then calling study->waitForFinished() on the main thread blocks because the process is still running after each command.

Instead you could try waitForReadyRead() or waitForBytesWritten().

  •  Tags:  
  • c qt
  • Related