如何获取父进程的ID
(hangwire发表于2001-12-26 17:00:47)
dwParentPID = pbi.InheritedFromUniqueProcessId;
// 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:[email protected], http://www.protect-me.com, http://www.codepile.com
#include
#include
#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;
}