[Qt-interest] How to capture stdout and redirect it to the gui?

Sergey Krupov sergey.krupov.1 at gmail.com
Thu Jan 27 19:31:14 CET 2011


27.01.2011 3:42, K. Frank пишет:
> Hello Qt!
>
> I would like to "capture" stdout and redirect it to a logging
> window, for example, a QTextEdit.
>
> Jochen Ulrich gave a good solution for doing this with std::cout
> a few years back, see:
>
>     http://lists.trolltech.com/qt-interest/2005-06/thread00166-0.html
>
> I am using this, and it works well for std::cout, but now I
> am using a C library that writes stuff to stdout (not C++'s
> std::cout), and I would like to capture this output as well.
>
> I am using Qt 4.6.1 on windows 7 with mingw.
>
> This is not overly urgent.  I found a posting that shows how
> to set "config += console" in the .pro file so that stdout output
> will appear in the console window from which I launch my Qt
> application.  So I can get the data this way, and make do.
>
> But I would prefer, if possible, to display the output in the
> gui, rather than a separate console window.
>
> Would someone know of a solution or have suggestions about
> things to try?
>
> Thanks.
>
>
> K. Frank
> _______________________________________________
> Qt-interest mailing list
> Qt-interest at qt.nokia.com
> http://lists.qt.nokia.com/mailman/listinfo/qt-interest

Here is simple example (written for Linux) how to capture output to 
stderr. You may modify it to capture output from stdout and stderr in cycle

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <pthread.h>

void* thread_func(void*)
{
fd_set set;
FD_ZERO (&set);
FD_SET (2, &set);

struct timeval timeout;
timeout.tv_sec = 30;
timeout.tv_usec = 0;

int status = select (FD_SETSIZE, &set, NULL, NULL, &timeout);
if(FD_ISSET(2, &set)) {
char buf[100];
int count = read(2, buf, sizeof(buf) - 1);
buf[count] = 0;
printf("GOT: %s", buf);
}
pthread_exit(NULL);
}

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

int stderr_stub[2] = {-1, -1};
close(2);
int status = pipe(stderr_stub);
if(status) {
printf("pipe error\n");
exit(EXIT_FAILURE);
}

pthread_t thread;
pthread_create(&thread, NULL, thread_func, NULL);

// writing to stderr
char test_string[] = "Hello from Sergey";
write(2, test_string, sizeof(test_string));

pthread_join(thread, NULL);
return (EXIT_SUCCESS);
}



More information about the Qt-interest-old mailing list