#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)
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;
}
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.