|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionSometimes, you might be in a situation when your application is launched by another program, which cannot be modified to change its behavior. If you can not grab any COM interface or a meaningful Windows handle, then the only thing left is the process handle to deal with. One thing you can do with such a handle is to try to do some interprocess synchronization. There are two programs included in the workspace, a startup MFC application that will merely launch the child, and the child application called GetParentProcID.exe that will latch onto its parent and wait for its termination. BackgroundUnfortunately, Win32 does not have an API that gives you the PID of the parent process, and you have to create it yourself. We will use functions found in Psapi.dll and in the Kernel32.DLL, that will be loaded programmatically. Using the codeIn short, we need to iterate through the processes running on the machine, identify the current process entry, and use it to retrieve the parent’s PID. We begin by getting the handle to a Toolhelp snapshot of the systems. hSnapShot = lpfCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0 );
This handle is used to iterate through the process entries and compare them against the current process ID: bContinue = lpfProcess32First( hSnapShot, &procentry ) ;
DWORD pid = 0;
// While there are processes, keep looping.
DWORD crtpid= GetCurrentProcessId();
while( bContinue )
{
if(crtpid == procentry.th32ProcessID)
pid = procentry.th32ParentProcessID;
procentry.dwSize = sizeof(PROCESSENTRY32) ;
bContinue = !pid && lpfProcess32Next( hSnapShot, &procentry );
}//while ends
The The parent process PID is the There are two things to note about this last function:
Once we have all the info about the parent, we can wait for its termination by calling while(dwres = WaitForSingleObject(hProcess, TIMEOUT) == WAIT_TIMEOUT)//wait up to TIMEOUT ms { printf("TimedOut waiting for %s after %d ms\n", pszName,TIMEOUT); } printf((WAIT_OBJECT_0 == dwres)? "waiting for parent termination SUCCEEDED\n" : "parent waiting FAILED\n");
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||