为什么 ReadFile() 不返回 0 ?程序尝试永远从管道读取数据
Why ReadFile() doesn't return 0 ? Program tries to read data from pipe forever
code:
这是来自更大的MS示例(http://msdn.microsoft.com/en-us/library/ms682499(VS.85).aspx)。当然,我之前尝试了整个示例,我在下面的截图是我将其剥离到问题的地方。问题是如果我得到的只是1
,我应该如何打破这个循环.如何发出没有更多数据要读取的信号?
(编译器是MiGW。
看起来 MS 示例已损坏,这是那里的评论之一:父进程需要关闭它在 CreateProcess() 调用后传递给子进程的句柄。不这样做将导致父级永远等待 ReadFile()。
#include <iostream>
#include <windows.h>
using namespace std;
int main() {
cout << "n->Start of parent execution.n";
SECURITY_ATTRIBUTES saAttr;
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
HANDLE g_hChildStd_OUT_Rd = NULL;
HANDLE g_hChildStd_OUT_Wr = NULL;
CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0);
STARTUPINFO siStartInfo;
PROCESS_INFORMATION piProcInfo;
ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
CreateProcess(NULL,
(char*)"cmd /c dir", // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
0, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
CHAR chBuf[4096];
DWORD dwRead;
// ~~~~~~this loop here~~~~~- how to break out of it ?
while(true) {
cout << "ReadFile: " << ReadFile( g_hChildStd_OUT_Rd, chBuf, 4096, &dwRead, NULL) << endl;
}
cout << "n->End of parent execution.n";
}
你试过所有代码吗?MSDN有一些句柄继承的东西。看起来管道的写入端没有关闭,因此 ReadFile 认为如果等待,会有更多内容需要读取。
编辑:
"CloseHandle(g_hChildStd_OUT_Wr);" 使读取在读取所有内容后终止,因此问题似乎是在子进程终止后写入结束永远不会完全关闭。但是,MSDN 示例似乎不需要它,因此您需要更仔细地查看为什么会这样。
相关文章:
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- IPC使用多个管道和分支进程来运行Python程序
- 为什么是谷神星协方差.计算()似乎永远运行而不返回?
- 密码登录程序将永远循环并显示不正确的结果
- 如何创建函数管道,以便函数一个接一个地运行?
- Gstreamer 管道从命令 lne 到 c 代码
- 外壳包装器句柄/执行交互式命令管道C++ UNIX
- 我想在C++中读取一些多个字符,但它永远不会读取第二个字符
- SFML 碰撞永远不会在我的系统中注册
- 将旧管道转换为现代 openGL 时出现问题
- 如何使用管道在父级和子级之间来回传递文件
- 在没有管理员权限的情况下连接到同一网络中的命名管道
- 如何测量管道延迟?
- 我如何使用此程序管道多个命令?C++
- 先进先出:一个进程永远不会从管道读取
- Node.js fs.open() 在尝试打开 4 个以上的命名管道 (FIFO) 后挂起
- 移动构造函数永远不会被调用
- 使用模板而不是虚拟方法的管道模式
- 为什么 ReadFile() 不返回 0 ?程序尝试永远从管道读取数据
- C++管道错误,管道永远等待