login007的备忘录
好吧,这里只是我用来静下心,做好记录的地方。

网络上搜集到得代码段,未经过测试,先记录下来以后查阅

// parent.cpp (Windows NT/2000)
//
// This example will show the method how you can retrieve the parent
// process ID on Windows NT/2000 using the NT Native API
// 
//
// (c)1999 Ashot Oganesyan K, SmartLine, Inc
// mailto:ashot@aha.ru, http://www.protect-me.com, http://www.codepile.com

#include <windows.h>
#include <stdio.h>

#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 (WINAPI *PROCNTQSIP)(HANDLE,UINT,PVOID,ULONG,PULONG);


PROCNTQSIP NtQueryInformationProcess;

DWORD GetParentProcessID(DWORD dwId);

void main(int argc, char* argv[])
{
    if (argc<2)
    {
       printf("Usage:\n\nparent.exe ProcId\n");
       return;
    }

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

    if (!NtQueryInformationProcess)
       return;

    DWORD dwId;
    sscanf(argv[1],"%lu",&dwId);

    printf("Parent PID for %lu is %lu\n",dwId,GetParentProcessID(dwId));

}

DWORD GetParentProcessID(DWORD dwId)
{
    LONG                      status;
    DWORD                     dwParentPID = (DWORD)-1;
    HANDLE                    hProcess;
    PROCESS_BASIC_INFORMATION pbi;

    // Get process handle
    hProcess = OpenProcess(PROCESS_QUERY_INFORMATION,FALSE,dwId);
    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;
}

  

posted on 2011-09-02 10:54  login007  阅读(2711)  评论(1编辑  收藏  举报