【发布时间】:2019-04-23 11:15:15
【问题描述】:
我正在使用CreateProcess() 运行cmd.exe(没有向用户显示物理窗口)并且需要处理输出。为此,我决定使用CreatePipe()。
我目前遇到一个问题,即我的所有输出都被读取和处理,但对ReadFile() 的最终调用挂起。四处搜索告诉我,我需要在读取之前关闭管道的写入端,这是解决此问题的方法,但我已经这样做了,但问题仍然存在。
这是我的代码:
// sw -> path to cmd.exe, ptr is the command
ok = CreateProcess(sw, ptr, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &StartupInfo, &ProcessInfo);
CloseHandle(hStdInPipeRead);
char buf[1024 + 1] = {};
DWORD dwRead = 0;
DWORD dwAvailable = 0;
DWORD testRes;
CloseHandle(hStdOutPipeWrite);
ok = ReadFile(hStdOutPipeRead, buf, 1024, &dwRead, NULL);
// String handling for initial read omitted for clarity
string temp = buf;
bool holdOff = false;
while (ok == TRUE)
{
buf[dwRead] = '\0';
OutputDebugStringA(buf);
puts(buf);
// ReadFile gets all the correct output from cmd here but it also hangs on the very last call. How to fix?
ok = ReadFile(hStdOutPipeRead, buf, 1024, &dwRead, NULL);
temp = buf;
// handle and store output
break;
}
CloseHandle(hStdOutPipeRead);
CloseHandle(hStdInPipeWrite);
【问题讨论】:
-
如果没有
sw和ptr值,很难推断出cmd的作用。您的管道在cmd退出之前一直有效。 -
为您创建 2 个管道对(4 个手柄)而不是 1 对(2 个手柄)?并从自身端使用异步管道端
-
您没有显示设置管道或 CreateProcess 参数的代码。请提供minimal reproducible example。
-
@RemyLebeau - 可以假设这通常是来自stackoverflow.com/a/55718264/6401656的复制粘贴
-
并且需要理解 - 只有当另一端的 所有 句柄都将关闭时,读取文件才会失败(使用
ERROR_BROKEN_PIPE)。因为这你需要关闭hStdOutPipeWrite并且它重复的句柄将在 cmd 退出时关闭。所以 cmd 在你的情况下不会退出