Getting the parent id of a process

Below is the code to return the parent id of a process, given a process id.
This can be helpful in circumstances when we have to scan all the running processes to find out the spawned processes from another process.

[code language="cpp"]
// change this method signature according to your requirements
BOOL GetParentPID( DWORD dwParentId, DWORD &dwChildProcessId, bool &bChildProcess, std::list &listParentIds)
{
	OSVERSIONINFO  osver ;
	HINSTANCE      hInstLib ;
	HANDLE         hSnapShot ;
	BOOL           bContinue ;
	// ToolHelp Function Pointers.
	HANDLE (WINAPI *lpfCreateToolhelp32Snapshot)(DWORD,DWORD) ;
	BOOL (WINAPI *lpfProcess32First)(HANDLE,LPPROCESSENTRY32) ;
	BOOL (WINAPI *lpfProcess32Next)(HANDLE,LPPROCESSENTRY32) ;
	hInstLib = LoadLibraryA( "Kernel32.DLL" ) ;
	if( hInstLib == NULL )
	{
		return false;
	}
	// Get procedure addresses.
	lpfCreateToolhelp32Snapshot=
		(HANDLE(WINAPI *)(DWORD,DWORD))
		GetProcAddress( hInstLib,
		"CreateToolhelp32Snapshot" ) ;
	lpfProcess32First=
		(BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))
		GetProcAddress( hInstLib, "Process32First" ) ;
	lpfProcess32Next=
		(BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))
		GetProcAddress( hInstLib, "Process32Next" ) ;
	if( lpfProcess32Next == NULL ||
		lpfProcess32First == NULL ||
		lpfCreateToolhelp32Snapshot == NULL )
	{
		FreeLibrary( hInstLib ) ;
		return false ;
	}
	// Get a handle to a Toolhelp snapshot of the systems
	// processes.
	hSnapShot = lpfCreateToolhelp32Snapshot(
		TH32CS_SNAPPROCESS, 0 ) ;
	if( hSnapShot == INVALID_HANDLE_VALUE )
	{
		FreeLibrary( hInstLib ) ;
		return false ;
	}
	PROCESSENTRY32 procentry;
	// Get the first process' information.
	memset((LPVOID)&procentry,0,sizeof(PROCESSENTRY32));
	procentry.dwSize = sizeof(PROCESSENTRY32) ;
	bContinue = lpfProcess32First( hSnapShot, &procentry ) ;
	DWORD pid = 0;
	// While there are processes, keep looping.
	DWORD  crtpid= dwParentId;
	while( bContinue )
	{
		if(procentry.th32ParentProcessID == dwParentId)
		{
			// add the ids of the processes with the parent id
			listParentIds.push_back(procentry.th32ProcessID);
		}
		procentry.dwSize = sizeof(PROCESSENTRY32) ;
		bContinue = lpfProcess32Next( hSnapShot, &procentry );
	}//while ends
	// Free the library.
	FreeLibrary( hInstLib ) ;
	return true;
}
[/code]

2 responses

  1. Jonathan Simon Jones Avatar
    Jonathan Simon Jones

    Do you need to know the parentID to use this function? Also in relation to this what is the parent ID?

    1. kmdarshan Avatar
      kmdarshan

      Hi Jonathan,
      I wrote this code a long time back ( more than 2 years ). I am assuming that we need to provide a child process ID, which will return a list of parent IDs.
      Thanks,
      Darshan

Leave a Reply

Your email address will not be published. Required fields are marked *