WIN通过子进程获取父进程ID

// ParentPid.cpp : Defines the entry point for the console application.
// 对着你的项目点击右键,依次选择:属性、配置属性、常规,然后右边有个“项目默认值”,下面有个2个MFC的使用选项

#include "stdafx.h"
#include <afx.h>
#include <Psapi.h>
#include <Windows.h>

#pragma comment (lib, "Psapi.lib")

#define MAX_PROCESS_LENGTH  (128)

// 获取进程名称
bool GetProcessName(DWORD processid,LPTSTR buf,int len)
{
    //make sure buf is valid and long enough
    buf[0]=0;
    if(processid ==8)
    {
        _tcscpy(buf, L"System");
        return true;
    }
    if(processid==0)
    {
        _tcscpy(buf, L"System Idle Process");
        return true;
    }
    HANDLE hProcess =OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,false,processid);
    if(hProcess == NULL)
    {
        _tcscpy(buf, L"unknown(OpenProcess error)");
        return false;	
    }
    HMODULE hModule;
    DWORD cbReturned;
    BOOL bret = EnumProcessModules(hProcess ,&hModule, sizeof(hModule), &cbReturned );
    if(bret)
        GetModuleBaseName(hProcess,hModule,buf,len);
    else{
        _tcscpy(buf, L"unknown(GetModuleBaseName error)");
    }
    CloseHandle( hProcess  ) ;
    return bret;
}

// 获取父进程ID
ULONG_PTR GetParentProcessId(int pid) 
{
    ULONG_PTR pbi[6];
    ULONG ulSize = 0;
    LONG (WINAPI *NtQueryInformationProcess)(HANDLE ProcessHandle, ULONG ProcessInformationClass,
        PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength);
    *(FARPROC *)&NtQueryInformationProcess =
        GetProcAddress(LoadLibraryA( "NTDLL.DLL"), "NtQueryInformationProcess" );

    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);

    if(NtQueryInformationProcess){
        if(NtQueryInformationProcess(hProcess, 0,
            &pbi, sizeof(pbi), &ulSize) >= 0 && ulSize == sizeof(pbi))
            return pbi[5];
    }
    return (ULONG_PTR)-1;
}


int _tmain(int argc, _TCHAR* argv[])
{
    int row = 1;
    if(argc <= 1) {
        wprintf(_T("%d) parameter error.\n"), row);
        return -1;
    }

    CString str = argv[1];
    int pid = _ttoi(str);
    CString strPrint;
    ULONG_PTR ppid;

    LPTSTR pName = (LPTSTR)malloc( sizeof(_TCHAR) * MAX_PROCESS_LENGTH );

    for(; ; row++){
        ppid = GetParentProcessId( pid );
        if(-1 == ppid ) {
            wprintf(_T("%d) No parent process.\n"), row);
            break;
        }

        if(!GetProcessName(ppid, pName, MAX_PROCESS_LENGTH)){
            wprintf(_T("%d) No parent process.\n"), row);
            break;
        }

        strPrint.Format(_T("%d) Pid[%d]'s parent is [%d][%s]."), row, pid, ppid, pName);
        wprintf(_T("%s\n"), strPrint.GetBuffer() );

        pid = ppid;
    }
    return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值