I create a child process using CreateProcess API. From the child process I need to fetch the parent\'s process id.
If my process tree have a child and a grand child.
wj32's answer should do what you need, but I figured I'd mention another way in case anyone else needs a ancestor at a different level. You can also take a snapshot enumerate the process tree and navigate the ancestors until you reach whatever level you're looking to reach as explained here.
The following example gets the process ID of the parent process (the process started the current one):
// Speed up build process with minimal headers.
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#include
#include
#include
#include
/* Macros for prettier code. */
#ifndef MAX_PATH
# define MAX_PATH _MAX_PATH
#endif
// Search each process in the snapshot for id.
BOOL FindProcessID(HANDLE snap, DWORD id, LPPROCESSENTRY32 ppe)
{
BOOL fOk;
ppe->dwSize = sizeof(PROCESSENTRY32);
for (fOk = Process32First( snap, ppe ); fOk; fOk = Process32Next( snap, ppe ))
if (ppe->th32ProcessID == id)
break;
return fOk;
}
// Obtain the process and thread identifiers of the parent process.
BOOL ParentProcess(LPPROCESS_INFORMATION ppi)
{
HANDLE hSnap;
PROCESSENTRY32 pe;
THREADENTRY32 te;
DWORD id = GetCurrentProcessId();
BOOL fOk;
hSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS|TH32CS_SNAPTHREAD, id );
if (hSnap == INVALID_HANDLE_VALUE)
return FALSE;
FindProcessID( hSnap, id, &pe );
if (!FindProcessID( hSnap, pe.th32ParentProcessID, &pe ))
{
CloseHandle( hSnap );
return FALSE;
}
te.dwSize = sizeof(te);
for (fOk = Thread32First( hSnap, &te ); fOk; fOk = Thread32Next( hSnap, &te ))
if (te.th32OwnerProcessID == pe.th32ProcessID)
break;
CloseHandle( hSnap );
ppi->dwProcessId = pe.th32ProcessID;
ppi->dwThreadId = te.th32ThreadID;
return fOk;
}
int _tmain(int argc, _TCHAR* argv[])
{
PROCESS_INFORMATION parentInformation;
if(!ParentProcess(&parentInformation)) {
_tprintf(TEXT("Fatal: Could not get parent information.\n"));
return 1;
}
_tprintf(TEXT("Parent Process ID: %ul\n"), parentInformation.dwProcessId);
return 0;
}