1. 程式人生 > >WIN通過子程序獲取父程序ID

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;
}