c++ - ReadFile卡在管道读取上

标签 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);

最佳答案

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

另外,Anonymous Pipe Operations

Asynchronous (overlapped) read and write operations are not supported by anonymous pipes(Create by 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);

关于c++ - ReadFile卡在管道读取上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55809972/

相关文章:

C++ 引用和引用参数

c++ - C++ 中的 using 指令和声明

c++ - 无法在 gdb 中设置断点

c++ - 如何编写一个使用 n 次三元条件语句的 C++ boolean 函数?

c++ - 如何遍历 map vector 中的 map ?

c# - 获取当前音量windows 8

c - 数字列表框

c# - 启动启动进程 B 的 Win32 进程 A——获取 B 的 ID/HWND

c - SB_THUMBTRACK 不重复发送

python - 如何从 Win32_PnPEntity 实例中提取特定属性?