为什么 ReadFile() 不返回 0 ?程序尝试永远从管道读取数据

Why ReadFile() doesn't return 0 ? Program tries to read data from pipe forever

本文关键字:永远 管道 数据 读取 程序 ReadFile 返回 为什么      更新时间:2023-10-16

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 示例似乎不需要它,因此您需要更仔细地查看为什么会这样。