ERROR_INVALID_HANDLE when calling GetModuleFileNameEx after CreateProcess

After a successful call to CreateProcess, I try to get the path to the created process using GetModuleFileNameEx (the lpApplicationName and lpCommandLine parameters may differ or be null so that in this case they are not reliable). The problem is that GetModuleFileNameEx failed with error 6 (ERROR_INVALID_HANDLE), leaving its buffer with invalid data. I cannot understand the reason, since CreateProcess succeeds and the process descriptor must be stored correctly in pi.hProcess.

Hope you can shed some light, thanks in advance!

EDIT: Update: I noticed that removing CREATE_SUSPENDED also fixes this problem, but I need this flag. How can i do

// Defining GetModuleFileNameExA function
typedef DWORD (WINAPI *fGetModuleFileNameExA)
(
    HANDLE hProcess,
    HMODULE hModule,
    LPSTR lpFilename,
    DWORD nSize
);
//Load dinamically DLL function on program startup:
fGetModuleFileNameExA _GetModuleFileNameExA = (fGetModuleFileNameExA) GetProcAddress( LoadLibraryA("Psapi.dll"), "GetModuleFileNameExA");

// **** OTHER UNRELATED CODE HERE ****


PROCESS_INFORMATION pi;

//This call succeeds
if (!CreateProcessW( ApplicationName, 
                    CommandLine, 
                    NewProcess.lpProcessAttributes, 
                    NewProcess.lpThreadAttributes,
                    NewProcess.bInheritHandles,
                    CREATE_SUSPENDED | CREATE_NEW_CONSOLE,
                    NULL,
                    CurrentDirectory,
                    &NewProcess.bufStartupInfo,
                    &pi)
       ) MessageBoxA(0, "Error creating process", "", 0);

    char ProcessPath[MAX_PATH];

//Problem here: call fails with error 6
if (!_GetModuleFileNameExA(pi.hProcess, NULL, ProcessPath, MAX_PATH)) {GetLastError();}

//Invalid data is displayed
MessageBoxA(0, ProcessPath, "GetModuleFileNameEx",0);
+1
1

CreateProcess MSDN:

, . DLL , . , GetExitCodeProcess.

...

WaitForInputIdle, , , . , CreateProcess , . , WaitForInputIdle, , .

+2

Source: https://habr.com/ru/post/1620934/


All Articles