如何检查带有给定的句柄的过程



方案:在App1中,我需要执行App2传递App1.Handle作为param。App2应该等到App1关闭。此后,App2应该用更新版本替换App1.exe文件。

  • 是否有更好的方法来更新运行的可执行文件?
  • 如果没有..在App2中,我知道App1。如果App1已关闭。如何从app1.handle?

编辑:

app1:

var
  ProcessHandle : THandle;
begin
  ProcessHandle := OpenProcess(PROCESS_ALL_ACCESS, False, GetCurrentProcessId());
  //Is PROCESS_ALL_ACCESS needed?
  ShellExecute(0, 'open', 'App2.exe', PChar(IntToStr(ProcessHandle)), '.', SW_SHOW);
end;

app2:

var
  SenderHandle : THandle;
begin
  if(ParamStr(1) <> '') then
  begin
    SenderHandle := StrToInt(ParamStr(1));
    WaitForSingleObject(SenderHandle, INFINITE);
    ShowMessage('App1 Terminated!');
    //Showmessage is executed when App1 is still running, what's wrong?
  end;
end;

App1.Handle表示窗口句柄。App2需要等待App1的 Process Hander 而等待。要获取App1的过程句柄,请使用以GetCurrentProcessId()为ID的OpenProcess(),或以GetCurrentProcess()作为源句柄的DuplicateHandle()。然后,您可以将手柄传递到App2,并使用WaitForSingleObject()等待App2等待它。当App1退出时,将发出句柄信号。然后App2可以关闭句柄并替换App1.exe。

为什么要等待使用PID终止该过程?为什么不尝试覆盖文件?只要该过程仍在运行,您就无法覆盖.exe文件。

即。类似:

WHILE NOT CopyFile(NewVersion,InstalledVersion) DO Sleep(100);

当然,您可以合并一个超时和其他保障措施,但是以上显示了另一种方法,而无需PID或其他值来测试...

最新更新