Skip to content
Advertisement

How to get the returned stdout of a program called with QProcess?

I am writing a program in Qt and currently using popen to run a linux command and read the output into a string:

    QString Test::popenCmd(const QString command) {
    FILE *filePointer;
    int status;
    int maxLength = 1024;
    char resultStringBuffer[maxLength];
    QString resultString = "";

    filePointer = popen(command.toStdString().c_str(), "r");
    if (filePointer == NULL) {
        return 0;
    }

    while (fgets(resultStringBuffer, maxLength, filePointer) != NULL) {
        resultString += resultStringBuffer;
    }
    status = pclose(filePointer);
    if (status == 0) {
        return resultString;
    } else {
        return 0;
    }
}

So I’d like to throw the above code away as I’d prefer to use higher level facilities provided by Qt if possible. Does anyone have an example of how to do this with QProcess or atleast a rough idea of how it could be done?

For what it’s worth, this will be run on Linux.

Thank you

Advertisement

Answer

Do like this:

void Process::runCommand(const QString &p_Command) {
    QProcess *console = new QProcess();
    console->connect(console, SIGNAL(readyRead()), this, SLOT(out()));
    console->connect(console, SIGNAL(finished(int)), this, SLOT(processFinished(int)));
    console->start(p_Command);
}

void Process::out() {
    QProcess *console = qobject_cast<QProcess*>(QObject::sender());
    QByteArray processOutput = console->readAll();
}

void Process::processFinished(int p_Code) {
    QProcess *console = qobject_cast<QProcess*>(QObject::sender());
    QByteArray processOutput = console->readAll() + QString("Finished with code %1").arg(p_Code).toLatin1();
}

Signal QProcess::finished() can be used to get the exit code of the process.

Advertisement