Solved

Using OpenProcess to obatin a valid process handle

Posted on 2004-10-06
3
885 Views
Last Modified: 2008-01-09
I am writing an application that is tracking (cpu usage and memory usage) of other applications I wrote.  To do this I need to obatin a valid handle to the process I want to track. I am trying to do this by using some code I got from msdn that takes in the exe name.  The code will loop through the processes and I can obtain the process name to see if it the process I am looking for, but it always returns a process handle of 0x000007cc for all processes.  GetLastError returns 5 or Invalid handel.  Why is it not returning the actual processes handle?



void ProcessTracker::setName(string name)
{
    _name = name;  //used for cpu needs to be intretated with handle

    DWORD aProcesses[1024], cbNeeded, cProcesses;
    unsigned int i;

    if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
    {
            return;
      }

      cProcesses = cbNeeded / sizeof(DWORD);

    for ( i = 0; i < cProcesses; i++ )
    {
          TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");

            HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
                                   PROCESS_VM_READ,
                                   FALSE, aProcesses[i] );

            DWORD err = GetLastError();

            if (NULL != hProcess )
            {
                  HMODULE hMod;
                  DWORD cbNeeded;

                  if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),
                         &cbNeeded) )
                  {
                        GetModuleBaseName( hProcess, hMod, szProcessName,
                                                   sizeof(szProcessName)/sizeof(TCHAR) );
                  
                        if(stricmp(szProcessName,name.c_str())==0)
                        {
                              _handle = hProcess;
                              CloseHandle(hProcess);
                              break;
                        }
                  }
            }

            CloseHandle( hProcess );
    }
}
0
Comment
Question by:nicoleheritage
  • 2
3 Comments
 

Author Comment

by:nicoleheritage
ID: 12240740
By the way.  I am using Microsoft VC++ 6.0 on Win XP
0
 
LVL 52

Accepted Solution

by:
Julian Hansen earned 200 total points
ID: 12241188
Are you sure OpenProcess is failing? OpenProcess should return NULL if it failes - if it doesn't the return value of GetLastError() is meaningless as it will hold the value of the last error encountered.

The fact that OpenProcess returns the same value each time is not an error. OpenProcess returns a handle which is an internal reference to an OS object. Because you are closing the handle after each iteration it is highly likely the next time you open a process you will get the same handle value back.

To illustrate - right after you do an OpenProcess on aProcesses[i] do

HANDLE hP2 = OpenProcess( PROCESS_QUERY_INFORMATION |
                                   PROCESS_VM_READ,
                                   FALSE, aProcesses[i+1] );

and add the corresponding close at the end for hP2. If you step through this you will see the second open for the next process in the list gets a different value from the first but always the same different value as you iterate.

HTH

0
 

Author Comment

by:nicoleheritage
ID: 12242942
You are right.  I moved the closehandle from the following into the class's destructor and everything worked.  

 if(stricmp(szProcessName,name.c_str())==0)
                    {
                         _handle = hProcess;
                         CloseHandle(hProcess);

thanks.  
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Entering a date in Microsoft Access can be tricky. A typo can cause month and day to be shuffled, entering the day only causes an error, as does entering, say, day 31 in June. This article shows how an inputmask supported by code can help the user a…
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

912 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now