Currently I have a main process that creates an anonymous pipe and a child process and then uses the pipe to redirect console output to the child process.
The pipe is created with CreatePipe
, the read handle is passed as the StdIn handle for the new process using CreateProcess
, and stdout of the main program is redirected to the write handle of the pipe using:
stdout->_file = _open_osfhandle( (long)m_hOutputWrite, _O_TEXT);
setvbuf( stdout, NULL, _IONBF, 0 );
This all works. The child process starts and the console output is redirected.
Now for the problem: If I call TerminateProcess
to end the child process, I can restore the main process's console output using freopen_s( &fp, "CON", "w", stdout )
or a variety of other methods after the child process is dead.
If the child process ends on its own (clicking the X in the corner, or calling, ExitProcess, etc), stdout is dead for good on the main process. Any attempts at reopening stdout have no effect. I'm not getting any errors -- just NO console output!!
Admittedly, I don't understand pipes and handle inheritance very well, so that could be a problem. I just don't know why TerminateProcess
allows the un-re-direction to work, and having the child die on its own causes this issue.
If you need more info, ask and I'll update the question. Thanks!
EDIT:
So, I have discovered, that if the pipe is broken by closing one end (like when the child process dies) and the main program writes ANYTHING to it with cout or printf, etc, I have the problem with stdout. If I can restore stdout before I write anything, everything works fine. So, TerminateProcess
is working because the child process dies and the console is restored before anything is written to the broken pipe. So, what now?