CreatePipe / CreateProcess无效读取句柄

时间:2018-03-21 06:36:52

标签: windows delphi winapi pipe

我尝试使用管道进行进程通信,但是尝试从Read句柄读取会导致错误。

首先,这里有一些测试代码来查看管道是否正常工作,但它没有:

procedure TestPipe;
const
  SecConst: TSecurityAttributes = (nLength: SizeOf(TSecurityAttributes); bInheritHandle: true);
var
  Security: TSecurityAttributes;
  PipeRead, PipeWrite: THandle;
  s: string;
begin
  Security:= SecConst;
  Win32Check(CreatePipe(PipeRead, PipeWrite, @Security, 0));
  Win32Check(SetStdHandle(STD_OUTPUT_HANDLE, PipeWrite));
  Win32Check(SetStdHandle(STD_INPUT_HANDLE, PipeRead));
  Writeln('555');
  Readln(s);  // <-- Hangs here!
  Assert(s = '555');
end;

程序挂起,而不是读取我写入管道的字符串。

以下是我想要稍作修改的实际代码:

procedure StartWorker;
const
  SecConst: TSecurityAttributes = (nLength: SizeOf(TSecurityAttributes); bInheritHandle: true);
var
  Security: TSecurityAttributes;
  PipeRead, PipeWrite: THandle;
  SI: TStartupInfo; PI: TProcessInformation;
  s: string;
begin
  Security:= SecConst;
  Win32Check(CreatePipe(PipeRead, PipeWrite, @Security, 0));
  Win32Check(SetStdHandle(STD_OUTPUT_HANDLE, PipeWrite));

  FillChar(SI, SizeOf(SI), 0);
  FillChar(PI, SizeOf(PI), 0);
  SI.cb:= SizeOf(SI);
  SI.dwFlags:= STARTF_FORCEOFFFEEDBACK or STARTF_USESTDHANDLES;
  SI.hStdInput:= PipeRead;
  SI.hStdOutput:= INVALID_HANDLE_VALUE;
  SI.hStdError:= INVALID_HANDLE_VALUE;
  s:= 'Worker.exe';
  UniqueString(s);
  Win32Check(CreateProcess(nil, PChar(s), nil, nil, false, 0, nil, nil, SI, PI));
  CloseHandle(PI.hThread);
  CloseHandle(PI.hProcess);
end;

在这种情况下,子进程获取无效的StdIn句柄。儿童过程只是做了一个无限的“阅读”过程。循环(并且应该对它读取的字符串执行某些操作)。首先打电话给&#39; Readln&#39;因I / O错误6&#39;而失败(句柄无效)。

0 个答案:

没有答案