jgpt
jgpt

Reputation: 139

Get a process executable name from process ID

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.

Upvotes: 5

Views: 19148

Answers (2)

hmjd
hmjd

Reputation: 121961

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:

Upvotes: 12

pritaeas
pritaeas

Reputation: 2093

According to this thread that error is returned when there's not enough information to return the filename.

Upvotes: 0

Related Questions