C++ 使用句柄从 CreateProcess() 收集输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2674237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:18:30  来源:igfitidea点击:

Using a handle to collect output from CreateProcess()

c++createprocess

提问by Stef

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.

我正在使用 CreateProcess() 从我的 GUI 应用程序在 Windows 中运行外部控制台应用程序。我想以某种方式收集输出以了解是否有错误。现在我知道我必须对 hStdOutput 做一些事情,但我不明白是什么。我是 C++ 新手,也是一个没有经验的程序员,实际上我不知道如何处理手柄或如何点亮管道。

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

问题:如何使用 hStdOutput 将输出读取到文件(例如)?

回答by Helge Klein

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.

Microsoft 在其知识库中有一个示例,演示了如何捕获子控制台进程的输出。基本原理是父进程创建管道(每个标准句柄一个重定向)并将句柄传递给 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

更多信息:如何使用重定向的标准句柄生成控制台进程