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.
Here is my 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) >0 then
begin
status := 1;
Synchronize(Sync);
end;
until dwRead < sizeof(buf);
until Running <> WAIT_TIMEOUT ;
status := 0;
Synchronize(Sync);
CloseHandle(PI.hProcess);
CloseHandle(PI.hThread);
end;