Reputation: 11
I'm curious - how can I get the PID of an executable by name, or a list of PIDs, in C++ on Windows? I've referred to this documentation:
Taking a Snapshot and Viewing Processes
When compiling and running this code, the process IDs are all in hexidecmial format. Is there a way to get the integer value of the PIDs instead?
For instance, is there a way to get the value:
10200
Instead of
0x000027D8
Do I have to actually convert the hexidecimcal value, or is there a way to extract the integer equivalent?
Upvotes: 0
Views: 1422
Reputation: 1838
GetProcessId function
Retrieves the process identifier of the specified process.
Read more Here
Code example (note DWORD definition A DWORD is a 32-bit unsigned integer ):
DWORD MyGetProcessId(LPCTSTR ProcessName) // non-conflicting function name
{
PROCESSENTRY32 pt;
HANDLE hsnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
pt.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(hsnap, &pt)) { // must call this first
do {
if (!lstrcmpi(pt.szExeFile, ProcessName)) {
CloseHandle(hsnap);
return pt.th32ProcessID;
}
} while (Process32Next(hsnap, &pt));
}
CloseHandle(hsnap); // close handle on failure
return 0;
}
int main()
{
DWORD pid = MyGetProcessId(TEXT("calc.exe"));
std::cout << pid;
if (pid == 0) { printf("error 1"); getchar(); }//error
return 0;
}
Upvotes: 1
Reputation: 598011
The PIDs themselves are already integers. The MSDN code is outputting the PIDs in hexadecimal format. Simply change 0x%08X
to %u
in the following 2 lines to output the PIDs in decimal format instead:
_tprintf( TEXT("\n Process ID = %u"), pe32.th32ProcessID );
...
_tprintf( TEXT("\n Parent process ID = %u"), pe32.th32ParentProcessID );
Upvotes: 0