Search code examples
c++qtqstringqtcorelibxslt

Capture my program's stderr output in Qt


I am writing a Qt GUI application that uses the libxslt library. libxslt always prints errors to stderr, but in certain cases it would be helpful for the user to see those messages displayed. Is there a way to capture the stderr output and put it in a QString?


Solution

  • There are two quick options:

    1) Wrap your usage around with an external process and use QProcess.

    This will introduce an external wrapper. This will not allow you to process the error "sometimes" off-hand. You would need some external processing for that.

    QProcess process;
    process.start("wrapper");
    process.waitForFinished();
    qDebug() << process.readAllStandardError();
    

    2) As per the famous Linux Programming Interface book example: redirect the stderr (2) file descriptor.

    This is a bit more complex, but it is better for avoiding the external process wrapper. It is also only posix compliant, so may not work without that. If you plan to use msvc, this may be a show-stopper. You would need to write the Windows backend then separately or use mingw.

    int pfd[2];
    pipe(pfd);
    // Do other things here.
    close(STDERR_FILENO);
    if (pfd[1] != STDERR_FILENO) {
        dup2(pfd[1], STDERR_FILENO);
        close(pfd[1]);
    }
    read(...);