windows - 关闭管道会使 DLL 的标准输出句柄无效
问题描述
我正在从外部 DLL 调用一个函数,该函数将其输出写入标准输出。为了捕获输出,我创建了一个监视线程,在其中我使用CreatePipe
和SetStdHandle
(下面的代码)将标准输出重定向到管道。问题是这段代码只能工作一次。如果多次执行,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;
解决方案
推荐阅读
- java - Eclipse添加外部Jar(websocket)
- javascript - 从一个组件路由到另一个 reactjs
- docker - 从 Gitlab 13.11.4 升级到 Gitlab 14.2.3
- node-notifier - 节点通知器在生产模式下不起作用
- java - Spring应用程序中的SaveAll方法
- node.js - Node读取文件时的空响应
- reactjs - 如何在 useState 挂钩中有多个状态
- javascript - 如何在 React.js 的页面中创建锁定警报模式?
- python - 在 Microsoft Bot Framework 中检索/访问 Bot 响应
- xamarin.forms - 绑定问题!将一页绑定到多页