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

Sergey Krupov sergey.krupov.1 at gmail.com
Thu Jan 27 20:13:51 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

Previouse example was incorrect. This one should work

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

void* thread_func(void *fd)
{
     int N = intptr_t(fd);

     fd_set set;
     FD_ZERO (&set);
     FD_SET (N, &set);

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

     int status = select (FD_SETSIZE, &set, NULL, NULL, &timeout);
     if(FD_ISSET(N, &set)) {
         char buf[100];
         int count = read(N, 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};
     if(pipe(stderr_stub)) exit(EXIT_FAILURE);
     close(2);
     dup2(stderr_stub[1], 2);
     close(stderr_stub[1]);

     pthread_t thread;
     pthread_create(&thread, NULL, thread_func, (void*) (intptr_t) 
stderr_stub[0]);

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

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



More information about the Qt-interest-old mailing list