|
|
|
How to obtain the PID (Process Identifier) of a process by process nameYou know what we can do if we know the PID of a process. So, obtaining the PID of the process of interest is worth trying. Of cause you can get the Process ID from the task manager. But here, we will see how we can obtain that programmatically. This is somewhat advanced task because the Win32 API functions we have to use cannot be used in the usual way. We have to load the appropriate dll (psapi.dll) at runtime by LoadLibrary and get the addresses of the functions by GetProcAddress. Here is the code. typedef BOOL (WINAPI *ENUMPROCESSES)(DWORD* pProcessIds, DWORD cb, DWORD* pBytesReturned); The function GetProcId() takes the process name as the argument and returns the PID of the process. If the process is not found, it returns -1. Because we are taking three functions from psapi.dll (GetModuleFileNameEx, EnumProcesses, EnumProcessModules) at runtime, we have to use function pointers to store the process addresses. The typedefs in the top are the definitions of the function pointers for three functions. Then comes the declarations of three function pointers. Then, lets try to understand the function. First, the library psapi.dll is loaded using LoadLibrary and the addresses of the three necessary functions are obtained and stored in the function pointers using GetProcAddress. Then, we obtain a list of PID s of all the processes in the system by calling EnumProcesses. Then, for each PID found, we obtain the module name by using functions EnumProcessModules and GetModuleFileNameEx. If the module name matches the name required, we return the appropriate PID. If no process ID has the name we required, we return -1. If there are more than one processes with the same name, still the function returns the PID of just 1 process. Its your task to edit the function appropriately if you need to obtain all the process identifiers. The source code of the sample program can be downloaded here from FrostCode. The application is written as a MFC dialog based application. If you are not familiar with MFC programming, go through our MFC Tutorial.
|