Using a handle to collect output from CreateProcess()

Stef picture Stef · Apr 20, 2010 · Viewed 23.4k times · Source

I am using CreateProcess() to run an external console application in Windows from my GUI application. I would like to somehow gather the output to know whether there were errors. Now I know I have to do something with hStdOutput, but I fail to understand what. I am new to c++ and an inexperienced programmer and I actually don't know what to do with a handle or how to light a pipe.

How do I get the output to some kind of variable (or file)?

This is what I have a the moment:

void email::run(string path,string cmd){


    WCHAR * ppath=new(nothrow) WCHAR[path.length()*2];
    memset(ppath,' ',path.length()*2);
    WCHAR * pcmd= new(nothrow) WCHAR[cmd.length()*2];
    memset(pcmd,' ',cmd.length()*2);

    string tempstr;


    ToWCHAR(path,ppath);  //creates WCHAR from my std::string
    ToWCHAR(cmd,pcmd);

    STARTUPINFO info={sizeof(info)};
    info.dwFlags = STARTF_USESHOWWINDOW;    //hide process

    PROCESS_INFORMATION processInfo;

    if (CreateProcess(ppath,pcmd, NULL, NULL, FALSE, 0, NULL, NULL, &info, &processInfo))
        {
        ::WaitForSingleObject(processInfo.hProcess, INFINITE);

        CloseHandle(processInfo.hProcess);
        CloseHandle(processInfo.hThread);
        }

    delete[](ppath);
    delete[](pcmd);
}

This code probably makes any decent programmer scream, but (I shouldn't even say it:) It works ;-)

The Question: How do I use hStdOutput to read the output to a file (for instance)?

Answer

Helge Klein picture Helge Klein · Apr 23, 2013

Microsoft has an example in its knowledge base that demonstrates how to capture the output of a child console process. The basic principle is that the parent process creates pipes (one per standard handle to redirect) and passes the handles to CreateProcess.

The child process does not need to be modified for this to work, which is important if you do not have control over the child's source.

More information: How to spawn console processes with redirected standard handles