我试图在Windows控制台应用程序(C/C++)中获取父进程(完整路径)的名称。看起来应该管用,但它失败了,我看不出我做错了什么。它正在成功获取父PID,但未能获取名称。如有任何更正,将不胜感激。

#include <Windows.h>
#include <stdio.h>
#include <tlhelp32.h>
#include <Psapi.h>

DWORD getParentPID(DWORD pid)
{
    HANDLE h = NULL;
    PROCESSENTRY32 pe = { 0 };
    DWORD ppid = 0;
    pe.dwSize = sizeof(PROCESSENTRY32);
    h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if( Process32First(h, &pe)) 
    {
        do 
        {
            if (pe.th32ProcessID == pid) 
            {
                ppid = pe.th32ParentProcessID;
                break;
            }
        } while( Process32Next(h, &pe));
    }
    CloseHandle(h);
    return (ppid);
}

int getProcessName(DWORD pid, PUCHAR fname, DWORD sz)
{
    HANDLE h = NULL;
    int e = 0;
    h = OpenProcess
    (
        PROCESS_QUERY_INFORMATION,
        FALSE,
        pid
    );
    if (h) 
    {
        if (GetModuleFileNameEx(h, NULL, fname, sz) == 0)
            e = GetLastError();
        CloseHandle(h);
    }
    else
    {
        e = GetLastError();
    }
    return (e);
}

int main(int argc, char *argv[]) 
{
    DWORD pid, ppid;
    int e;
    char fname[MAX_PATH] = {0};
    pid = GetCurrentProcessId();
    ppid = getParentPID(pid);
    e = getProcessName(ppid, fname, MAX_PATH);
    printf("PPID=%d Err=%d EXE={%s}\n", ppid, e, fname);
}

其他信息:
openprocess返回5(错误访问被拒绝)。如果按建议添加PurryVxMyRead,则返回299(ErrRyPultAlgRead)。我可以打开当前进程,但不能打开父进程。

最佳答案:

OpenProcessPROCESS_VM_READ
h = OpenProcess
    (
    PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
    FALSE,
    pid
    );

同时看看梅卡普提到的可能的复制品