【问题标题】:How to know the executable name that launches an application?如何知道启动应用程序的可执行文件名?
【发布时间】:2015-05-08 19:45:49
【问题描述】:

如何确定启动 C++ 应用程序的可执行文件?

例如:我的应用程序名称是 (a.exe) 并且还有另一个应用程序名为 (b.exe)。我如何知道 a.exe 何时已使用 b.exe 启动?

【问题讨论】:

  • 检查argv[0] 以获取启动程序的名称。您无法以简单的方式获取父进程的名称..
  • @πάνταῥεῖ,在这种情况下,他想要父母的argv[0]。 AFAIK 没有标准的语言(或任何语言,可能)。那么这是哪个操作系统?窗户?
  • 假设windows,见this question如何获取父PID。还有this question如何从PID中获取文件名。

标签: c++ winapi


【解决方案1】:

我找到了一种方法,谢谢Wimmel

要获取进程 ID,您可以使用 GetParentProcessId()。你将需要这个功能:

ULONG_PTR GetParentProcessId() // By Napalm @ NetCore2K
{
    ULONG_PTR pbi[6];
    ULONG ulSize = 0;
    LONG (WINAPI *NtQueryInformationProcess)(HANDLE ProcessHandle, ULONG ProcessInformationClass,
    PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength); 
    *(FARPROC *)&NtQueryInformationProcess = 
    GetProcAddress(LoadLibraryA("NTDLL.DLL"), "NtQueryInformationProcess");
    if(NtQueryInformationProcess){
        if(NtQueryInformationProcess(GetCurrentProcess(), 0, &pbi, sizeof(pbi), &ulSize) >= 0 && ulSize == sizeof(pbi))
            return pbi[5];
    }
    return (ULONG_PTR)-1;
}

从进程 ID ProcessName(GetParentProcessId()) 获取进程名称。

然后你将需要这个函数:

char* ProcessName(int ProcessId){
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if(hSnapshot) {
        PROCESSENTRY32 pe32;
        pe32.dwSize = sizeof(PROCESSENTRY32);
        if(Process32First(hSnapshot,&pe32)) {
            do {
                int th32ProcessID = pe32.th32ProcessID;
                if (th32ProcessID == ProcessId)
                    return pe32.szExeFile;
            } while(Process32Next(hSnapshot,&pe32));
         }
         CloseHandle(hSnapshot);
    }
    return 0;
}

【讨论】:

  • 请记住,进程 ID 会被回收,因此不能保证 100% 准确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-31
  • 2017-01-22
  • 2014-03-19
  • 1970-01-01
相关资源
最近更新 更多