redirecting stdio for sequential programs in an MFC dialog

Dennis Foreman 0 Reputation points
2023-03-10T12:49:14.4566667+00:00

My C++ MFC dialog creates 2 child processes sequentially. I redirect STDOUT to separate files for each of the programs (and restore to default after each one runs). STDOUT from program 1 gets sent to its file as expected. Program 2 STDOUT disappears. Both programs return 0. I know Program 2 runs because a MessageBox it creates for debugging appears. To remove any other effects, I have reduced Program 2 to just: std::cout<<"aha"<<std::endl;

Is there anything I should know about doing this? PS. I have no access to the source code for the REAL programs 1 and 2.

Developer technologies | C++
{count} votes

1 answer

Sort by: Most helpful
  1. RLWA32 49,541 Reputation points
    2023-03-11T08:12:14.6933333+00:00

    Although the CRT will create inheritable files, the STARTUPINFO struct uses Win32 HANDLE types, not FILE* pointers returned from CRT functions.

    For example, to obtain the low-level HANDLE for use with STARTUPINFO from a CRT FILE* pointer -

    HANDLE hFile{ INVALID_HANDLE_VALUE };
    FILE *fp = _tfopen(_T("Created by ConsoleApplication1.txt"), _T("w"));
    if (fp)
        hFile = reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(fp)));
    if (hFile != INVALID_HANDLE_VALUE)
    {
    //   CreateProcess code using hFile in STARTUPINFO
    }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.