Details
-
Bug
-
Resolution: Won't Do
-
Not Evaluated
-
None
-
5.10.0
-
None
-
Desktop Qt 5.10.0 clang 64bit
Description
Hi, I don't know if I did anything wrong here. QProcess is behaving strangely for me.
#include <QCoreApplication> #include <QProcess> #include <QStringList> #include <QDebug> #include <QThread> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QProcess proc; proc.setProgram("/bin/bash"); QStringList args; args << "-c" << "for i in `seq 5`; do echo $i; sleep 1; done"; proc.setArguments(args); proc.setReadChannel(QProcess::StandardOutput); proc.start(QProcess::ReadOnly); // proc.waitForFinished(); while(1) { if (proc.bytesAvailable() > 0) { QByteArray qb = proc.readAllStandardOutput(); qDebug() << "out " << qb << endl; } else { qDebug() << "nothing" << endl; } QThread* th = QThread::currentThread(); th->sleep(1); } return a.exec(); }
It seems that
proc.bytesAvailable() > 0
is never true, unless I wait for the process to exit
proc.waitForFinished()
before checking the output.
Without waiting I only get "nothing nothing nothing..."
With waitForFinished the code correctly prints "out 1\n2\n3\n4\n5\n"
Basically I want to be able to read from stdout of a child process while the child is running, instead of after the child exits.
PS: after further inspection, the code only works if I spin with "waitForReadyRead".
#include <QCoreApplication> #include <QProcess> #include <QStringList> #include <QDebug> #include <QThread> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QProcess proc; proc.setProgram("/bin/bash"); QStringList args; args << "-c" << "for i in `seq 5`; do echo $i; sleep 1; done"; proc.setArguments(args); proc.setReadChannel(QProcess::StandardOutput); proc.start(QProcess::ReadOnly); while(1) { proc.waitForReadyRead(); if (proc.bytesAvailable() > 0) { QByteArray qb = proc.readAllStandardOutput(); qDebug() << "out " << qb << endl; } else { qDebug() << "nothing" << endl; } } return a.exec(); }
In other word, bytesAvailable() only returns > 0, (and after further testing, I found signal readReady only gets fired) when waitForReadyRead is called. Is this the expected behavior?
I do not see this mentioned in the docs.