title: ReadFile blocking when reading from pipe
body: <p>I want to read a console program output. The problem is that ReadFile deadlocks my thread. Even when process exists still the same. I heard that you must close Write Pipe but when doing so it does not read nothing.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>var
    saSec : TSecurityAttributes;
    hRead, hWrite : THandle;
    SI : TStartupInfo;
    PI : TProcessInformation;
    Running,dwRead : DWORD;
    buf : array [0..1024] of AnsiChar;
    data : AnsiString;
  begin
    saSec.nLength := sizeof(TSecurityAttributes);
    saSec.bInheritHandle := false;
    saSec.lpSecurityDescriptor := nil;
  
    if CreatePipe(hRead, hWrite, @saSec, 0) then
    begin
       FillChar(SI, Sizeof(TStartupInfo), #0);
       FillChar(PI, Sizeof(TProcessInformation), #0);
       SI.hStdInput := hRead;
       SI.hStdOutput := hWrite;
       SI.hStdError := hWrite;
       SI.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
       SI.wShowWindow := SW_HIDE;
  
       if CreateProcess(nil, PChar('openvpn' + cert), @saSec, @saSec, False, NORMAL_PRIORITY_CLASS, nil, nil, SI, PI) then
       begin
            data := '';
            repeat
              Running := WaitForSingleObject(PI.hProcess, 100);
              repeat
                    FillChar(buf, sizeof(buf), #0);
                    ReadFile(hRead, buf, sizeof(buf), dwRead, nil);
                    data := data + buf;
                     if Pos('sequence completed', data) &gt;0 then
                    begin
                      status := 1;
                      Synchronize(Sync);
                    end;
              until dwRead &lt; sizeof(buf);
  
            until Running &lt;&gt; WAIT_TIMEOUT ;
            status := 0;
            Synchronize(Sync);
            CloseHandle(PI.hProcess);
            CloseHandle(PI.hThread);
       end;
  </code></pre>