簡體   English   中英

為什么ReadFile()不返回0? 程序試圖永遠從管道讀取數據

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

碼:

這是來自更大的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);” 一旦讀取了所有內容,就會使讀取終止,所以看起來問題似乎是在子進程終止后,write end永遠不會完全關閉。 但是,MSDN示例似乎並不需要它,因此您需要更仔細地查看為什么會出現這種情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM