获取父进程ID

时间:2023-12-15 15:06:38

本程序主要功能是:获取某程序的ParentProcessID

直接上代码:

 // 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<)
{
printf("Usage:\n\nparent.exe ProcId\n");
return;
} NtQueryInformationProcess = (PROCNTQSIP)GetProcAddress(
GetModuleHandle("ntdll"),
"NtQueryInformationProcess"
); if (!NtQueryInformationProcess)
return; DWORD dwId;
sscanf(argv[],"%lu",&dwId); printf("Parent PID for %lu is %lu\n",dwId,GetParentProcessID(dwId)); } DWORD GetParentProcessID(DWORD dwId)
{
LONG status;
DWORD dwParentPID = (DWORD)-;
HANDLE hProcess;
PROCESS_BASIC_INFORMATION pbi; // Get process handle
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION,FALSE,dwId);
if (!hProcess)
return (DWORD)-; // 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;
}