Frank Chang
Frank Chang

Reputation: 1

Is it possible to get the WINAPI process handle by the process name without iterating through all processes

Good afternoon, Is it possible to get the WINAPI process handle by its name without walking through all the processes? I know how to WINAPI process handle by its name by iterating through all the processes:

     HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);      
     if (Process32First(snapshot, &entry) == TRUE){         
        while (Process32Next(snapshot, &entry) == TRUE)         
        {             
            if (stricmp(entry.szExeFile, ProcessName ) == 0){                   
                HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);                  
                // measure process memory usage                
                CloseHandle(hProcess);             
            }         
        }     
      }      
      CloseHandle(snapshot);   

However, it seems like it would take a significant amount of time to iterate through the process snapshot. Thank you.

Upvotes: 0

Views: 1809

Answers (1)

user405725
user405725

Reputation:

Each process has a unique ID but not unique name. There could be multiple processes with the same name. So it is impossible, as it is impossible, for example, to get an entry from std::map by value w/o iterating trough everything. What you can do, however, is to write a function that gives you a list of IDs by name, that will be reusable, but still will have to iterate. Why do you worry about performance here? I believe it is nothing comparing to opening of the handle and process memory measurement.

Upvotes: 1

Related Questions