您的位置:首页 > 其它

windows 下获取父进程pid

2017-08-31 11:15 1431 查看
DWORD GetParentProcessID(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;

}

控制台中需要加入下面代码

#include <wtypes.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 (__stdcall *PROCNTQSIP)(HANDLE,UINT,PVOID,ULONG,PULONG);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: