0

I want to run a qprocess (the program adb) and when the process is finished return the results to the calling function. However, there's every possibility that adb could find itself in a loop, printing error messages such as "ADB server didn't ACK" to stdout, not ever finishing. I need to trap these errors.

   QProcess run_command;
   connect(&run_command,SIGNAL(readyReadStandardOutput()),this,SLOT( dolog() ));       
   QString result=RunProcess("adb connect 192.168.1.100");

    ...

   QString MainWindow::RunProcess(QString cstring)
     {

    run_command.start(cstring);

      // keep gui active for lengthy processes.                      

       while(run_command.state() != QProcess::NotRunning)  
          qApp->processEvents();

      QString command=run_command.readAll();
      return command;  // returns nothing if slot is enabled.
    }

    void MainWindow::dolog()
         {
            QString logstring = run_command.readAllStandardOutput();
              if (logstring.contains("error condition")
                 logfile("Logfile:"+logstring);

         }

If I enable the signal/slot, dolog() prints stdout to a logfile, but RunProcess returns a blank string. If I disable the signal/slot, RunProcess() returns the qprocess output as expected.

Alan
  • 1,265
  • 4
  • 22
  • 44
  • 6
    Forget that `processEvents()` exists. 99% of the time it's used wrong, and that's the case here. You can write perfectly good applications, hundreds of thousands of lines long, that don't call it even once. If you want to run a process and get its output, you should attach one or more slots to relevant signals of the process. You also don't want to use `readAllStandardOutput`, but process each line separately by doing `while (run_command.canReadLine()) { auto line = run_command.readLine(); ... }` – Kuba hasn't forgotten Monica Oct 25 '16 at 21:18

1 Answers1

1

First you need to identify which output stream the command in question is using for its errors. It is very like stderr so you would need to connect to the readyReadStandardError() signal instead.

For the command itself I would recommend to split it into command and arguments and use the QProcess::start() overload that takes the command and a list of arguments. Just more robust than to rely on a single string being correctly separated again.

Kevin Krammer
  • 5,159
  • 2
  • 9
  • 22