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;
}