确定当前应用的父进程 [英] Determine the parent process of the current app

查看:21
本文介绍了确定当前应用的父进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了这个实用程序 (exe),可以从这个主机应用程序中调用它.而且我更喜欢只能从主机应用程序调用该实用程序.从外部或其他主机运行它应该立即终止该实用程序.

I wrote this utility (exe) which can be called from within this host application. And I'd prefer it that the utility can only be called from the host application. Running it from the outside or a different host should terminate the utility immediately.

有没有办法找出哪个进程启动了我的实用程序?

Is there a way to find out which process launched my utility?

感谢您的回复.

推荐答案

您可以使用 CreateToolhelp32Snapshot 函数枚举正在运行的进程列表,然后是 Process32First 函数以获取 th32ParentProcessID 这是创建此进程(其父进程)的进程的标识符.

You can use the CreateToolhelp32Snapshot function to enumerate the running process list and then the Process32First function to get the th32ParentProcessID which is the identifier of the process that created this process (its parent process).

请参阅此示例.

uses
  Psapi,
  Windows,
  tlhelp32,
  SysUtils;

function GetTheParentProcessFileName(): String;
const
  BufferSize = 4096;
var
  HandleSnapShot  : THandle;
  EntryParentProc : TProcessEntry32;
  CurrentProcessId: DWORD;
  HandleParentProc: THandle;
  ParentProcessId : DWORD;
  ParentProcessFound  : Boolean;
  ParentProcPath      : String;

begin
  ParentProcessFound := False;
  HandleSnapShot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);   //enumerate the process
  if HandleSnapShot <> INVALID_HANDLE_VALUE then
  begin
    EntryParentProc.dwSize := SizeOf(EntryParentProc);
    if Process32First(HandleSnapShot, EntryParentProc) then    //find the first process
    begin
      CurrentProcessId := GetCurrentProcessId(); //get the id of the current process
      repeat
        if EntryParentProc.th32ProcessID = CurrentProcessId then
        begin
          ParentProcessId := EntryParentProc.th32ParentProcessID; //get the id of the parent process
          HandleParentProc := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, ParentProcessId);
          if HandleParentProc <> 0 then
          begin
              ParentProcessFound := True;
              SetLength(ParentProcPath, BufferSize);
              GetModuleFileNameEx(HandleParentProc, 0, PChar(ParentProcPath),BufferSize);
              ParentProcPath := PChar(ParentProcPath);
              CloseHandle(HandleParentProc);
          end;
          break;
        end;
      until not Process32Next(HandleSnapShot, EntryParentProc);
    end;
    CloseHandle(HandleSnapShot);
  end;

  if ParentProcessFound then
    Result := ParentProcPath
  else
    Result := '';
end;

这篇关于确定当前应用的父进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆