简体   繁体   中英

How to get integer PID of process?

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?

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM