get process name from process id (win32)

David Chen picture David Chen · Nov 5, 2010 · Viewed 37.1k times · Source

I need to get a list of all processes on a windows system including names and PID.
EnumProcess can obtain a list of pids, but how do I get the process name from the pid? I don't want to call OpenProcess on the process as that doesn't always work (like if the other process is run by a different user).

Answer

Cyclonecode picture Cyclonecode · Dec 3, 2011

Ýou can get the process identifier and name for all running processes using the ToolHelp API.
The following code will display the pid and name for each process.

void showProcessInformation() {
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if(hSnapshot) {
        PROCESSENTRY32 pe32;
        pe32.dwSize = sizeof(PROCESSENTRY32);
        if(Process32First(hSnapshot, &pe32)) {
            do {
               printf("pid %d %s\n", pe32.th32ProcessID, pe32.szExeFile);
            } while(Process32Next(hSnapshot, &pe32));
         }
         CloseHandle(hSnapshot);
    }
}