Using a handle to collect output from CreateProcess()

梦想与她 提交于 2019-12-04 18:03:59

问题


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)?


回答1:


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



来源:https://stackoverflow.com/questions/2674237/using-a-handle-to-collect-output-from-createprocess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!