Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read from QProcess?

Tags:

c++

qt

qprocess

I have this simple C++ program:

int main(int argc, char *argv[])
{

    QCoreApplication a(argc, argv);

    QProcess ps;
    QByteArray ba;

    ps.start("ls J:");
    ba = ps.readAllStandardOutput();
    char *someData = ba.data();

    cout << "Testing QProcess ..." << endl;
    cout << someData << endl;
    cout << "done!" << endl;

    return a.exec();
}

The output is:

Testing QProcess ...


done!

If I run "ls J:" from Windows cmd it works. What am I missing?

like image 364
Amani Avatar asked Feb 18 '23 01:02

Amani


1 Answers

Use QIODevice::waitForReadyRead() in a loop, and only after that returns, then call readAllStandardOutput(). As it says in the docs, QProcess::readAllStandardOutput() will read all available data, but will not wait. And before you start reading, you need to wait that process is started with QProcess::waitForStarted().

Quick untested partial code, replace line ba = ps.readAllStandardOutput(); with this:

if (ps.waitForStarted(-1)) {
    while(ps.waitForReadyRead(-1)) {
        ba += ps.readAllStandardOutput();
    }
}
// else report error or whatever

That should exit the loop when there is error or child process terminates, but keep reading until then, with no timeout.

Note: in a "regular" Qt program, you would have event loop running, and then you would not call waitForReadyRead() or other similar convenience functions. They would block the event loop and stop everything else too. In such a program, you would preferably use signals and slots, or alternatively start mucking about with threads (but that's generally not preferred, it just adds unnecessary complexity).

like image 64
hyde Avatar answered Feb 26 '23 18:02

hyde