Sunday, February 22, 2009

[VC++] Getting parent Process ID of current process

If you need to get the Process ID of your parent application, after taking a snapshot of all the process you may need to iterate and get the current process information. See the below code snippet for obtaining the parent Process ID.
HANDLE hSnapShot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
PROCESSENTRY32 stProcessEntry;
// Get the current process id
DWORD dwPID= GetCurrentProcessId();
// To store Parent process id
DWORD dwParentPID = 0;
// Get the first process
BOOL bContinue = Process32First( hSnapShot, &stProcessEntry );
// Loop for all the process
while( bContinue )
{
// If current process get the parent id
if( dwPID == stProcessEntry.th32ProcessID)
{
// Now dwParentPID have the parent process id
dwParentPID = stProcessEntry.th32ParentProcessID;
break;
}
// If not current process Get next process
bContinue = Process32Next( hSnapShot, &stProcessEntry );
}
// Show the parent Process ID
char szParentPID[5];
itoa( dwParentPID, szParentPID, 10 );
MessageBox( szParentPID );
There is an alternate way for getting parent process id using an undocumented API ZwQueryInformationProcess()

No comments: