【发布时间】:2016-02-19 06:41:20
【问题描述】:
我正在使用 CreateProcess 启动一个进程,我想等待该进程完成,或者等待任何要写入标准输出的内容,该标准输出正在通过匿名管道传输。下面的代码不起作用,因为 WaitForMultipleObjects 不断返回 stdout 管道,即使没有可读取的内容。 有没有办法等待管道?我等不及阅读了,因为如果过程完成,我还需要继续。 我也不能等到过程完成而不检查管道,因为它可能会溢出。有什么想法吗?
if (::CreateProcess(
(!application_name.empty() ? application_name.c_str() : NULL), // Application/Executable name, if supplied.
lpCommandLine, // Arguments or Executable and Arguments
NULL, // Process Attributes
NULL, // Thread Attributes
TRUE, // Inherit handles
CREATE_NO_WINDOW, // Create flags
NULL, // Environment (Inherit)
current_directory.c_str(), // Working Directory
&m_startup_info, // Startup Info
&process_info // Process Info
))
{
HANDLE handles[2];
bool waiting = true;
handles[0] = process_info.hProcess;
handles[1] = m_read_stdout; // previously created with CreatePipe. One end handed to CreateProcess
// Must process stdout otherwise the process may block if it's output buffer fills!!
while (waiting)
{
DWORD r = ::WaitForMultipleObjects(2, handles, FALSE, INFINITE);
switch (r)
{
case WAIT_OBJECT_0+0:
waiting = false;
break;
case WAIT_OBJECT_0+1:
AppendSTDOUTFromProcess(output);
break;
default:
ATLASSERT(FALSE);
break;
}
}
}
【问题讨论】:
-
应该可以使用一些复杂的重叠 I/O:stackoverflow.com/a/51448441/1833960