1. 程式人生 > >[Delphi]如何通過程序控制代碼判斷該程序是否已退出?

[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.