ReadFile挂在管道读取上

时间:2019-04-23 11:15:16

标签: c++ winapi

我正在使用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);

1 个答案:

答案 0 :(得分:0)

如果您设置SECURITY_ATTRIBUTES.bInheritHandle = true,则子进程将继承管道的句柄,关闭的管道的写句柄仅是父进程的句柄,子进程中仍然有一个句柄(子进程stdout),并且尚未在cihld进程中关闭,Readfile失败并仅在所有写句柄关闭或发生错误时返回。

此外,Anonymous Pipe Operations

  

不支持异步(重叠)读写操作   通过匿名管道(由CreatePipe创建)。

因此,如果仍然需要向子进程发送命令来执行cmd,则应将ReadFile放入线程中。 而且,如果您不再需要,请终止子进程:

TerminateProcess(ProcessInfo.hProcess,0);
WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
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);