콘텐츠로 건너뛰기

부모 프로세스 ID 구하기

부모 프로세스 ID는 NtQueryInformationProcess 함수를 통해서 쉽게 구할 수 있습니다.

아래 구문과 같이 NtQueryInformationProcess 함수는 Output 파라미터로 ProcessInformation 구조체를 반환하는데 해당 구조체의 InheritedFromUniqueProcessId 변수가 부모 프로세스 ID 입니다.

구문

__kernel_entry NTSTATUS NtQueryInformationProcess(
  [in]            HANDLE           ProcessHandle,
  [in]            PROCESSINFOCLASS ProcessInformationClass,
  [out]           PVOID            ProcessInformation,
  [in]            ULONG            ProcessInformationLength,
  [out, optional] PULONG           ReturnLength
);
C++
typedef struct _PROCESS_BASIC_INFORMATION {
    NTSTATUS ExitStatus;
    PPEB PebBaseAddress;
    ULONG_PTR AffinityMask;
    KPRIORITY BasePriority;
    ULONG_PTR UniqueProcessId;
    ULONG_PTR InheritedFromUniqueProcessId;
} PROCESS_BASIC_INFORMATION;
C++

코드

#include <iostream>
#include <windows.h>
#include <tchar.h>

ULONG_PTR GetParentProcessId()
{
	BOOL loaded = FALSE;
	ULONG_PTR parent_process_id = 0;
	ULONG_PTR pbi[6];
	ULONG size = 0;

	HMODULE handle_ntdll = GetModuleHandle(_T("ntdll.dll"));

	if (handle_ntdll == NULL)
	{
		loaded = TRUE;
		handle_ntdll = LoadLibrary(_T("ntdll.dll"));
	}

	typedef NTSTATUS(WINAPI* _LPNTQUERYINFORMATIONPROCESS)(HANDLE, ULONG, PVOID, ULONG, PULONG);
	_LPNTQUERYINFORMATIONPROCESS _NtQueryInformationProcess = reinterpret_cast<_LPNTQUERYINFORMATIONPROCESS>(GetProcAddress(handle_ntdll, "NtQueryInformationProcess"));

	if (_NtQueryInformationProcess)
	{
		if (_NtQueryInformationProcess(GetCurrentProcess(), 0, &pbi, sizeof(pbi), &size) >= 0 && size == sizeof(pbi))
		{
			parent_process_id = pbi[5];
		}
	}

	if (handle_ntdll != NULL && loaded)
	{
		FreeLibrary(handle_ntdll);
	}

	return parent_process_id;
}

int main()
{
	std::cout << "Current PID : " << GetCurrentProcessId() << " / Parent PID : " << GetParentProcessId() << "\n";

	return 0;
}
C++

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다