问题描述
如果ShellExecuteEx返回false,则应该关闭该句柄吗?:
In case which ShellExecuteEx returns false, should the handle be closed?:
function EditAndWait(const AFileName : string) : boolean;
var
Info: TShellExecuteInfo;
begin
FillChar(Info, SizeOf(Info), 0);
Info.cbSize := SizeOf(Info);
Info.lpVerb := 'edit';
Info.lpFile := PAnsiChar(AFileName);
Info.nShow := SW_SHOW;
Info.fMask := SEE_MASK_NOCLOSEPROCESS;
Result := ShellExecuteEx(@Info);
if(Result) then
begin
WaitForSingleObject(Info.hProcess, Infinite);
CloseHandle(Info.hProcess);
end else
begin
//should I close the process handle?
end;
end;
更一般而言,如何检查手柄是否应该关闭?
More generally, how can I check if an handle should be closed?
推荐答案
仅在以下情况下,您才返回过程句柄:
You are only returned a process handle if:
- 您包括了
SEE_MASK_NOCLOSEPROCESS
和 - 函数调用成功,并且
- 该操作已通过创建新流程解决.
如果前两个条件成立,但第三个条件成立,则将向您返回值为零的流程句柄.因此您的代码应为:
In case the first two conditions hold, but not the third, then you will be handled back a process handle with value zero. So your code should be:
Result := ShellExecuteEx(@Info);
if Result and (Info.hProcess<>0) then
begin
WaitForSingleObject(Info.hProcess, Infinite);
CloseHandle(Info.hProcess);
end;
如果我们非常学究,可能会在WaitForSingleObject
和CloseHandle
上进行错误检查.坦率地说,在这种情况下,我很难为此感到兴奋.可以从哪些故障模式中恢复?
If we were being very pedantic we might look for error checking on WaitForSingleObject
and CloseHandle
. Frankly though, I find it hard to get excited about that in this instance. What are the possible failure modes that could be recovered from?
您可能会问我的意思:
好吧,完全有可能通过回收现有过程来解决shell动作.在这种情况下,可能不会为您返回流程句柄.这将使代码陷入僵局,因为您没有什么可等待的,不必介意没有关闭的句柄.您只需要接受这种情况就可以了.
Well, it's entirely possible for a shell action to be resolved by re-cycling an existing process. In which case you may not be returned a process handle. And that puts the kibosh on your code because you have nothing to wait on, never mind no handle to close. You'll just have to accept that such scenarios are beyond you.
文档中这样说:
最后,请允许我祝贺您认真对待错误检查和避免泄漏的问题.如此多的开发人员似乎无视此问题,无论他们被告知多少次.很高兴您听取了最近提出的问题的注释,并努力改进您的代码.干得好!
Finally, may I congratulate you on taking seriously the issues of error checking and leak avoidance. So many developers seem to ignore this issue, no matter how many times they are told. It's nice that you have listened to comments at recent questions and made the effort to improve your code. Well done!
这篇关于如何检查手柄是否应该关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!