Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a process executable name from process ID

Tags:

windows

winapi

I am currently trying to get the names of a list of programs whose pid I have.

The program is run as administrator, but GetModuleFileNameEx fails with error code 5.

I open the program with OpenProcess(PROCESS_TERMINATE,PROCESS_QUERY_INFORMATION) and I have the SE_DEBUG_PRIVILEGE enabled.

like image 623
jgpt Avatar asked Dec 22 '22 05:12

jgpt


1 Answers

The process handle passed to GetModuleFileNameEx() requires PROCESS_QUERY_INFORMATION and PROCESS_VM_READ access rights.

This worked for me:

HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
                       FALSE,
                       6088);
if (0 == h)
{
    std::cerr << "OpenProcess() failed: " << GetLastError() << "\n";
}
else
{
    char exe_path[2048] = {};

    if (GetModuleFileNameEx(h, 0, exe_path, sizeof(exe_path) - 1))
    {
        std::cout << exe_path << "\n";
    }
    else
    {
        std::cerr << "GetModuleFileNameEx() failed: " <<
            GetLastError() << "\n";
    }
    CloseHandle(h);
}

However, as others have pointed out (and is also stated in documentation for GetModuleFileNameEx()) there are safer ways to acquire this information:

  • GetProcessImageFileName()
  • QueryFullProcessImageName()
like image 106
hmjd Avatar answered Jan 05 '23 08:01

hmjd