本文介绍了获取父进程名称 (Windows)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to get the name of the parent process (full path) in a Windows Console application (C/C++). It looks like it should work, but it is failing and I can't see what I am doing wrong. It is successfully getting the parent PID, but failing on getting the name. Any corrections would be appreciated.

#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 (ERROR_ACCESS_DENIED).如果我按照建议添加 PROCESS_VM_READ,它将返回 299 (ERROR_PARTIAL_COPY).我可以打开当前进程,但不能打开父进程.


Additional information:OpenProcess is returning 5 (ERROR_ACCESS_DENIED). If I add PROCESS_VM_READ as suggested, it returns 299 (ERROR_PARTIAL_COPY). I can open the current process, but not the parent process.

推荐答案

使用额外的 PROCESS_VM_READ 标志调用 OpenProcess,它应该可以工作:

Call OpenProcess with additional PROCESS_VM_READ flag and it should work:

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

还要看一下 Mekap 提到的可能的重复项

Also look at the possible duplicate mentioned by Mekap

这篇关于获取父进程名称 (Windows)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 11:40
查看更多