Search code examples
c++winapipid

C++ Windows - Get PIDs of process by executable file path


It's known and often asked how to get the full path to an executable from its PID. However, I need the opposite: I need to find the PID of the process from an absolute path to its executable.

Is there a simple way to do that, or should I fetch all PIDs and compare the executable path manually?

Why do I need that? I need to terminate junk instances of this process without killing other processes which have the same name as the process I should terminate.


Solution

  • There is no direct API call to get the process ID of an absolute path. As you surmised, you will have to enumerate all processes until you find the path you are interested in, then you will have its process ID. Look at EnumProcesses() or CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS) for that. See Process Enumeration on MSDN for examples.