Introduction
There are several ways to get the process id (and its handle afterwards) for any running process. One of them is by using functions that are available in PSAPI.DLL, which is distributed in the Microsoft� Platform Software Development Kit (SDK).The same information is generally available through the performance data.
One of the performance objects is 'Process' whose index is 230. The 'Process' object has several counters, one of them is 'ID Process' whose index is 784. A function called GetProcessID
runs through the performance objects and counters and retrieves the process id for the required process name.
The following sample shows you how to retrieve the process handle by performance data.
The Sample
std::vector<DWORD> SetOfPID;
GetProcessID("Rundll32",SetOfPID);
if (SetOfPID.empty())
{
printf("Process is not running\n");
}
else
{
for (int i=0;i < SetOfPID.size(); i++)
{
printf("Process ID is %d\n", SetOfPID[i]);
HANDLE hProcess = OpenProcess(
PROCESS_ALL_ACCESS,FALSE,SetOfPID[i]);
CloseHandle(hProcess);
}
}
More of my articles using performance counters
Updates
My first version returned only the first running instance. Since the process name is not unique I changed my code so it returns set of process id's.
- 13.1.03 - I release the allocation of
PERF_DATA_BLOCK
at the end of the function
- 19.3.03 - I add call to
RegCloseKey(HKEY_PERFORMANCE_DATA)
at the end of the function
- 15.6.03 - Using none case-sensitive comparison for checking process existance.
- 24.5.04 - Changed the first argument to
RegQueryValueEx
from "Global" (which retrieves the whole counters) to a string that specifies the specific process object and process-id counter. This change enables fast query.
- 25.8.04 - Source and demo updated