Search code examples
c++cwinapistdoutwindows-console

Redirect stdout to parent process console window


I want to achieve following situation:

  • parent process (ie cmd.exe has its own console)
  • child process myapp.exe should create new console window
  • in child process, writing to stdout should write to parent process console
  • if stdout of child process is redirected to a file, keep it that way

I already managed to create separate console in that way:

#include <windows.h>
#include <wincon.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>

int main(int argc, char* argv[])
{
    printf("output displayed in parent process\n");

    FreeConsole();
    AllocConsole();

    printf("output displayed in child process console\n");

    // how do I redirect stdout to 
    // that one I've had before FreeConsole?

    return 0;
} 

(it works fine in situation when stdout is redirected to file: myapp.exe > out.txt)

I've already tried many things, but none worked.

int main(int argc, char* argv[])
{
    printf("output displayed in parent process\n");

    HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);

    FreeConsole();
    AllocConsole();

    printf("output displayed in child process console\n");

    SetStdHandle(STD_OUTPUT_HANDLE,hStdOut);
    printf("no success 1\n");        

    return 0;
} 

int main(int argc, char* argv[])
{
    printf("output displayed in parent process\n");

    HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
    int fd = _open_osfhandle((intptr_t)hStdOut, _O_TEXT);

    FreeConsole();
    AllocConsole();

    printf("output displayed in child process console\n");

    FILE* hf = _fdopen( fd, "w" );
    *stdout = *hf;
    setvbuf( stdout, NULL, _IONBF, 0 );

    printf("no success 2\n");        

    return 0;
} 

Solution

  • A process can only write directly to the console it is attached to. If a child process is created with its own console, or allocates its own console once started, it can't subsequently write to the parent's console.

    If the parent process creates an anonymous pipe it can use the write handle as the child process's stdout. The parent process would need to service the pipe; e.g. it might have a thread to read data from the pipe and write it to its own console.

    The child process would not have to worry whether it was writing to a file or the parent process. It would all be normal I/O to stdout.