/StdoutRedirector

Redirect current process's stdout to QTextEdit

Primary LanguageC++

#Redirect current process's stdout to one Control widget.

Note: This class can only be used in Qt5, as QWindowsPipeReader which is introduced in Qt5.0 is used.

Implementation

Windows

  • Normally, we need to create pipe with CreatePipe(), then attach stdout to it's write end with SetStdHandle(), then read from pipe's read end with ReadFile().

  • But the CRT has already completed initialization before the application gets a chance to call SetStdHandle(); the three low I/O handles 0, 1, and 2 have already been set up to use the original OS handles. So we must deal with this layer using posix api _dup2() too.

  • Anonymous pipes created with CreatePipe() do not support asynchronous I/O, so named pipe is used.

Posix

  • First, we create a pipe, then make the writable end of the pipe the new stdout, and finally, read from the readable part of the pipe.

  • QSocketNotifier is used in order to monitor the activity of the pipe-read-end.

  • Note that QSocketNotifier will keep emitting signal if data exists in the pipe, while our readyRead() only emit when new data arrival, so QRingBuffer is used as a buffer.

Issues

  • [Windows]Can't capture the stdout output generated by another dlls.

If the dll compiled with a c/c++ run-time which is different from the run-time used by current application, or the run-time staticly linked to the dll or application, we will encounter this problem.

The reason is that, the DLL grabs the stdout handles when it is loaded, which took place before we changed the stdout handles. Dynamically load the DLL after changing the stdout handles will be helpful in this case.

  • [Windows]Can't capture the output of qDebug()

When the application build as a GUI application(without CONFIG += console in the .pro file), the debug messages will be send to the Debuger using the system api OutputDebugString().

OutputDebugString(reinterpret_cast<const wchar_t *>(logMessage.utf16()));

If CONFIG+=console is added to the .pro file, the debug message will be sent to the stderr.

fprintf(stderr, "%s", logMessage.toLocal8Bit().constData());

Reference