首页 > 解决方案 > 关闭管道会使 DLL 的标准输出句柄无效

问题描述

我正在从外部 DLL 调用一个函数,该函数将其输出写入标准输出。为了捕获输出,我创建了一个监视线程,在其中我使用CreatePipeSetStdHandle(下面的代码)将标准输出重定向到管道。问题是这段代码只能工作一次。如果多次执行,DLL 在尝试输出某些内容时会抛出“无效句柄”异常。我把它缩小到这CloseHandle(PipeWrite)条线。如果我将其注释掉,它就会开始按预期工作。为什么关闭此管道会使 DLL 的标准输出句柄永久无效?

const
  SecConst: TSecurityAttributes = (nLength: SizeOf(TSecurityAttributes); bInheritHandle: true);
var
  Security: TSecurityAttributes;
  hStdOld, PipeRead, PipeWrite: THandle;
begin
  Security := SecConst;
  CreatePipe(PipeRead, PipeWrite, @Security, 0);
  hStdOld := GetStdHandle(STD_OUTPUT_HANDLE);
  SetStdHandle(STD_OUTPUT_HANDLE, PipeWrite);

  while not Terminated do
  begin
    if ReadPipe(PipeRead, FOutput) > 0 then
    begin
      Synchronize(SendOutput);
    end;

  end;
  SetStdHandle(STD_OUTPUT_HANDLE, hStdOld);
  CloseHandle(PipeRead);
  CloseHandle(PipeWrite); //problematic call
end;

标签: windowsdelphidllconsolestdout

解决方案


推荐阅读