读取文件挂在管道读取上

ReadFile hanging on pipe reading

本文关键字:读取 管道 文件      更新时间:2023-10-16

我正在使用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] = '';
    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,子进程将继承管道的句柄,你关闭的管道的写入句柄只是父进程的,子进程中仍然有一个句柄(子进程的stdout(,并且在cihld进程中尚未关闭,Readfile失败,仅在所有写入句柄关闭或发生错误时才返回。

此外,匿名管道操作。

不支持异步(重叠(读取和写入操作 通过匿名管道(由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] = '';
    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);