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


本文整理自网络,侵删。

 
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.

相关阅读 >>

Delphi控件安装与删除

Delphi - system.runerror

Delphi执行cmd命令

Delphi 字符串替换函数[单元文件 sysutils]

Delphi tstreamwriter快速写入文件

Delphi中updown组件的使用方法

Delphi fmx 获取控件句柄

Delphi 对gzip解压

Delphi 将listview保存为txt

Delphi中实现控件的拖拽

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...