In the Win32 API, given a PID, how can I determine path on disk to the executable?

winapi

Solution

You should open the process using OpenProcess to get a process handle and then use the handle to get path using GetModuleFileNameEx API function.

HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, _PID_);
if (hProcess)
{
    TCHAR path[MAX_PATH];
    if (GetModuleFileNameEx(hProcess, NULL, path, sizeof(path)))
    {
        MessageBox(0, path, "The path", MB_ICONINFORMATION);
    }
    CloseHandle(hProcess);
}

If I remember correctly, using "PROCESS_QUERY_INFORMATION | PROCESS_VM_READ" will be enough to get process handle for path retrieve. If it failed, use PROCESS_ALL_ACCESS then.

Problem

In Win32, I've obtained a process id for a certain running process. Now I'd like to determine the path on the file system where the executable for the process resides. eg. if "tasklist" shows the "image name" to be "foobar.exe" and the PID to be 1234. The executable is located in c:\Program Files (x86)\Acme Corp\foobar.exe Which Win32 API call will accept the PID 1234 and give me the path "c:\Program Files (x86)\Acme Corp\foobar.exe"?

Original source