我尝试使用管道进行进程通信,但尝试从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句柄。子进程只是执行一个无限的“Readln”循环(并且应该对它读取的字符串执行某些操作)。第一次调用“Readln”失败,并出现“I/O error 6”(句柄无效)。
1条答案
按热度按时间kiz8lqtg1#