0

How can you determine the executable that launches an application with C++?

For example: my application name is (a.exe) and there is another application named (b.exe). How can I know when a.exe has been launched with b.exe or not?

Max Lybbert
  • 19,717
  • 4
  • 46
  • 69
a7md0
  • 429
  • 2
  • 10
  • 20
  • 2
    Check `argv[0]` to get the name of the program launched. You cannot get the parent's process name in a simple way.. – πάντα ῥεῖ May 08 '15 at 19:46
  • 3
    @πάνταῥεῖ, in this case he wants the parent's `argv[0]`. AFAIK there is no standard way to do it in the language (or any language, probably). So which OS is this? Windows? – Brian Cain May 08 '15 at 19:48
  • 6
    Asuming windows, see [this question](http://stackoverflow.com/q/5321914/33499) how to get the parent PID. And [this question](http://stackoverflow.com/q/23593688/33499) how to get the filename from the PID. – wimh May 08 '15 at 20:05

1 Answers1

1

I found a way to do this, thanks Wimmel.

To get the Process Id you can use GetParentProcessId(). And you will need this function:

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;
}

to get the Process Name from Process Id ProcessName(GetParentProcessId()).

And then you will need this function:

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;
}
laurisvr
  • 2,724
  • 6
  • 25
  • 44
a7md0
  • 429
  • 2
  • 10
  • 20