[Delphi]如何通过进程句柄判断该进程是否已退出?

来源:互联网 发布:apache windows下载 编辑:程序博客网 时间:2024/05/16 06:56
GetExitCodeProcess
    看似可以,但是仔细看MSDN,有这么一句话:“Warning  If a process happens to return STILL_ACTIVE (259) as an error code, applications that test for this value could end up in an infinite loop.” 很明显,我们不能保证一个进程不会返回一个STILL_ACTIVE (259)做为退出码,也就是说GetExitCodeProcess返回了STILL_ACTIVE 并不代表这个进程还没有结束。此时该进程可能已经结束(并返回259做为退出码)或者没有结束。此路不通。

WaitForSingleObject
    这才是正途。进程本质上是一个”内核对象“,可以用Wait系列的API函数来等待其结束。其实我们做多线程同步时也用过WaitFor....只不过那时是wait一个线程句柄。

    delphi中实现如下:

unit SysUtils2;
{作者: 袁晓辉 blog.csdn.net/uoyevoli}

interface

uses Windows;

//返回值代表是否成功
//如果返回True,HasExited 代表进程是否已经结束
function ProcessHasExited(ProcessHandle: THandle; out HasExited: Boolean): Boolean;

implementation

function ProcessHasExited(ProcessHandle: THandle; out HasExited: Boolean): Boolean;
var
  WaitResult: DWORD;
begin
  Result :=False;
  WaitResult := WaitForSingleObject(ProcessHandle, 0);
  Result := WaitResult <> WAIT_FAILED;
  HasExited := WaitResult = WAIT_OBJECT_0;
end;
end.
原创粉丝点击