读取文件挂在管道读取上
ReadFile hanging on pipe reading
我正在使用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);
相关文章:
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 先进先出:一个进程永远不会从管道读取
- C++命名管道客户端读取的字节不会超过 4096 字节
- 如何使客户端在将数据写入 C++ 管道之前检查服务器是否完成了从管道的读取操作
- 使用命名管道块的读取文件,尽管使用重叠
- 使用管道从 STDIN 读取分叉进程时出现问题
- 管道未正确读取数据
- read() 在 select() 阻塞之后,当从生成的进程从管道读取时
- 读取文件挂在管道读取上
- 使用两个不同的管道C 读取和写入相同的过程
- 启动子进程时的争用条件导致从管道读取挂起
- 如何在C++中读取进化邮件管道
- 为什么从管道读取时libc++getline会阻塞,而libstdc++getline不会
- 无法读取在cmd.exe管道下启动的进程的输出
- C++双向管道-在循环中尝试从子进程读取时卡住
- 父进程不读取管道表单
- 如何使用 mingw 读取管道并将其放入字符串变量中
- 正在读取管道输入
- 阻塞读取管道的调用
- Linux -子读取管道接收发送到标准输出的调试消息