5,696,576 members and growing! (14,734 online)
Email Password   helpLost your password?
General Programming » Threads, Processes & IPC » Processes     Intermediate

Get Parent Process PID

By dmihailescu

How to get the parent process PID, and how to use it in the child process.
VC6, C++Windows, NT4, Win2K, WinXPVS6, Visual Studio, Dev

Posted: 20 Mar 2005
Updated: 22 Mar 2005
Views: 46,811
Bookmarked: 12 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
13 votes for this Article.
Popularity: 3.38 Rating: 3.04 out of 5
4 votes, 30.8%
1
0 votes, 0.0%
2
2 votes, 15.4%
3
3 votes, 23.1%
4
4 votes, 30.8%
5

Sample Image

Introduction

Sometimes, 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.

Background

Unfortunately, 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 code

In 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 PROCESSENTRY32 structure we got from our GetParentProcID function is passed down to the WaitForParentToFinish, that does the synchronization:

The parent process PID is the th32ParentProcessID data member of this structure.

There are two things to note about this last function:

  1. We need to get a process handle that can be used for synchronization (hence the SYNCHRONIZE flag):
    HANDLE hProcess = OpenProcess(
                   SYNCHRONIZE | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
                   FALSE, procentry.th32ParentProcessID ) ;
  2. The parent’s file name can be retrieved using EnumProcessModules and grabbing the name from the first module by calling GetModuleFileNameEx:
    if( EnumProcessModules( hProcess, &hMod, sizeof( hMod ), &dwSize2 ) )
    {
        if( !GetModuleFileNameEx( hProcess, hMod,
                    szFileName, sizeof( szFileName ) ) )
        {.......

Once we have all the info about the parent, we can wait for its termination by calling WaitForSingleObject:

    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");

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

dmihailescu


Decebal Mihailescu is a software engineer with interest in .Net, C# and C++.
Occupation: Web Developer
Location: United States United States

Other popular Threads, Processes & IPC articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 3 of 3 (Total in Forum: 3) (Refresh)FirstPrevNext
QuestionSorrymemberGzd200723:05 22 Aug '06  
GeneralI can not compile the program!memberGzd200723:03 22 Aug '06  
GeneralRe: I can not compile the program!memberVytas9:47 18 Sep '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 22 Mar 2005
Editor: Smitha Vijayan
Copyright 2005 by dmihailescu
Everything else Copyright © CodeProject, 1999-2008
Web20 | Advertise on the Code Project