获取进程及父进程的两种方式(转)

https://www.cnblogs.com/jkcx/p/7463506.html

#include <windows.h>
#include <TlHelp32.h>
#include <stdio.h>
#include <wtypes.h>
#include <iostream>

#define ProcessBasicInformation 0  

typedef struct
{
    DWORD ExitStatus;
    DWORD PebBaseAddress;
    DWORD AffinityMask;
    DWORD BasePriority;
    ULONG UniqueProcessId;
    ULONG InheritedFromUniqueProcessId;
}   PROCESS_BASIC_INFORMATION;


// ntdll!NtQueryInformationProcess (NT specific!)  
//  
// The function copies the process information of the  
// specified type into a buffer  
//  
// NTSYSAPI  
// NTSTATUS  
// NTAPI  
// NtQueryInformationProcess(  
//    IN HANDLE ProcessHandle,              // handle to process  
//    IN PROCESSINFOCLASS InformationClass, // information type  
//    OUT PVOID ProcessInformation,         // pointer to buffer  
//    IN ULONG ProcessInformationLength,    // buffer size in bytes  
//    OUT PULONG ReturnLength OPTIONAL      // pointer to a 32-bit  
//                                          // variable that receives  
//                                          // the number of bytes  
//                                          // written to the buffer   
// ); 
typedef LONG(__stdcall *PROCNTQSIP)(HANDLE, UINT, PVOID, ULONG, PULONG);


DWORD GetParentProcessIDBYID(DWORD dwProcessId)
{
    LONG                        status;
    DWORD                       dwParentPID = (DWORD)-1;
    HANDLE                      hProcess;
    PROCESS_BASIC_INFORMATION   pbi;

    PROCNTQSIP NtQueryInformationProcess = (PROCNTQSIP)GetProcAddress(
        GetModuleHandle(L"ntdll"), "NtQueryInformationProcess");

    if (NULL == NtQueryInformationProcess)
    {
        return (DWORD)-1;
    }
    // Get process handle
    hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwProcessId);
    if (!hProcess)
    {
        return (DWORD)-1;
    }

    // Retrieve information
    status = NtQueryInformationProcess(hProcess,
        ProcessBasicInformation,
        (PVOID)&pbi,
        sizeof(PROCESS_BASIC_INFORMATION),
        NULL
        );

    // Copy parent Id on success
    if (!status)
    {
        dwParentPID = pbi.InheritedFromUniqueProcessId;
    }

    CloseHandle(hProcess);

    return dwParentPID;

}






int GetProcessID(WCHAR* ProcessName)
{

    HANDLE PHANDLE = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
    if (PHANDLE == INVALID_HANDLE_VALUE)
    {
        printf_s("创建进行快照失败
");
        return -1;
    }

    PROCESSENTRY32 pe32;
    pe32.dwSize = sizeof(pe32);
    pe32.dwFlags = sizeof(pe32);
    BOOL hProcess = Process32First(PHANDLE, &pe32);

    while (hProcess)
    {
        //std::wcout << pe32.szExeFile << "
";
        //std::wcout << pe32.th32ParentProcessID << "
";

        if (!wcscmp(pe32.szExeFile, ProcessName))
        {
            return pe32.th32ProcessID;
        }

        hProcess = Process32Next(PHANDLE, &pe32);
    }

    return 0; // operation failed (process was not found)
}

int GetParentProcessID(WCHAR* ProcessName)
{

    HANDLE PHANDLE = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
    if (PHANDLE == INVALID_HANDLE_VALUE)
    {
        printf_s("创建进行快照失败
");
        return -1;
    }

    PROCESSENTRY32 pe32;
    pe32.dwSize = sizeof(pe32);
    pe32.dwFlags = sizeof(pe32);
    BOOL hProcess = Process32First(PHANDLE, &pe32);

    while (hProcess)
    {
        //std::wcout << pe32.szExeFile << "
";
        //std::wcout << pe32.th32ParentProcessID << "
";

        if (!wcscmp(pe32.szExeFile, ProcessName))
        {
            return pe32.th32ParentProcessID;
        }

        hProcess = Process32Next(PHANDLE, &pe32);
    }

    return 0; // operation failed (process was not found)
}



void C2W(const char* szSrc, WCHAR* wszDst, int nMaxLen)

{

    int vMinLen = MultiByteToWideChar(CP_ACP, 0, szSrc, -1, NULL, 0);

    if (vMinLen > nMaxLen)

    {

        MessageBoxA(NULL, szSrc, "转换成UNICODE字串失败", MB_ICONWARNING);

        return;

    }

    MultiByteToWideChar(CP_ACP, 0, szSrc, -1, wszDst, vMinLen);

}

void main()
{
    
    char proc[64];
    WCHAR buf[64];
    scanf_s("%s", &proc, 63);
    
    //printf("进程:%s
", proc);

    C2W(proc, buf, sizeof(buf));

    int pid = GetProcessID(buf);
    printf("进程ID:%d
", pid);

    int ppid = GetParentProcessID(buf);
    printf("父进程ID:%d
", ppid);

    int ppid2 = GetParentProcessIDBYID(pid);
    printf("父进程ID2:%d
", ppid2);
    //printf("%d", Attach(buf));
    system("pause
");
}

  在不同的系统中获取的进程的名字方式不一致。

void CProcess::PrintProcessNameAndID( DWORD processID )
{
    CString str;
    HMODULE hMod;
    DWORD cbNeeded;
    HANDLE hProcess = INVALID_HANDLE_VALUE;
    PROCESS_BASIC_INFORMATION pbi = {0};
    char szProcessName[MAX_PATH] = "<unknown>";
    TCHAR szImageFileName[MAX_PATH] = {0}; 
    OSVERSIONINFOEX osver = { 0 };
    tagProcess tagpro;// = {0};

    osver.dwOSVersionInfoSize = sizeof(osver);
    GetVersionEx((OSVERSIONINFO*)&osver);
    EnablePrivilege();
    
    hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID );

    if (processID == 0)
    {
        //System Idle Process
        //null
        //没有父进程
        strcpy_s(szProcessName, MAX_PATH, "System Idle Process");
        NtQueryInformationProcess(hProcess, ProcessBasicInformation, (PVOID)&pbi, sizeof(PROCESS_BASIC_INFORMATION), NULL);
    }
    else if (processID == 4)
    {
        //System
        //C:Windowssystem32
toskrnl.exe
        //父进程为0
        strcpy_s(szProcessName, MAX_PATH, "System");
        NtQueryInformationProcess(hProcess, ProcessBasicInformation, (PVOID)&pbi, sizeof(PROCESS_BASIC_INFORMATION), NULL);
    }
    else
    {
        if (INVALID_HANDLE_VALUE != hProcess )
        {
            if (osver.dwMajorVersion < 5) //2000
            {
                EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded);
                GetModuleFileNameEx(hProcess, hMod, szProcessName, sizeof(szProcessName));
            }
            else if (osver.dwMajorVersion == 5) //xp or 2003
            {
                GetProcessImageFileName(hProcess, szProcessName, sizeof(szProcessName));
            }
            else if (osver.dwMajorVersion >= 6) // >win7
            {
                DWORD dwPathNameSize = sizeof(szProcessName);
                QueryFullProcessImageName(hProcess, 0, szProcessName, &dwPathNameSize);
            }

            NtQueryInformationProcess(hProcess, ProcessBasicInformation, (PVOID)&pbi, sizeof(PROCESS_BASIC_INFORMATION), NULL);
        }
        
    }

    if (hProcess != INVALID_HANDLE_VALUE)
    {
        CloseHandle(hProcess);
        hProcess = INVALID_HANDLE_VALUE;
    }

    tagpro.pid = processID;
  //这里需要判断下当前的父进程id是否存在,负责会导致构建父子关系表出错。遍历时查不到父进程。 tagpro.ppid
= pbi.InheritedFromUniqueProcessId; CString strName = szProcessName; strName = strName.Right(strName.GetLength() - strName.ReverseFind('\') - 1); tagpro.strProcessName = strName; m_cMyProc.Add(processID, tagpro); str.Format(_T("%s pid:%u, ppid:%u "), szProcessName, processID, pbi.InheritedFromUniqueProcessId); // Print the process name and identifier. OutputDebugString(str); } BOOL CProcess::InitProcessList(void) { DWORD aProcesses[1024], cbNeeded, cProcesses; unsigned int i; if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ) return FALSE; cProcesses = cbNeeded / sizeof(DWORD); for ( i = 0; i < cProcesses; i++ ) { PrintProcessNameAndID(aProcesses[i]); } //排列父子关系 //m_cMyProc.Sort(); //m_cMyProc.Print(); //m_cMyProc.RemoveALl(); //m_cMyProc.Print(); return FALSE; }
原文地址:https://www.cnblogs.com/Fightingbirds/p/11320593.html