NtQueryInformationProcess – 꿈꾸는 개발자 https://studioys.me #개발 #일상생활 #생각 Sun, 29 Sep 2024 13:04:54 +0000 ko-KR hourly 1 https://wordpress.org/?v=6.8 https://studioys.me/wp-content/webpc-passthru.php?src=https://studioys.me/wp-content/uploads/2024/09/cropped-그림1-32x32.png&nocache=1 NtQueryInformationProcess – 꿈꾸는 개발자 https://studioys.me 32 32 부모 프로세스 ID 구하기 https://studioys.me/%eb%b6%80%eb%aa%a8-%ed%94%84%eb%a1%9c%ec%84%b8%ec%8a%a4-id-%ea%b5%ac%ed%95%98%ea%b8%b0/ https://studioys.me/%eb%b6%80%eb%aa%a8-%ed%94%84%eb%a1%9c%ec%84%b8%ec%8a%a4-id-%ea%b5%ac%ed%95%98%ea%b8%b0/#respond Sun, 29 Sep 2024 13:04:52 +0000 https://studioys.me/?p=793

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

구문

NtQueryInformationProcess 함수 원형은 다음과 같습니다.

__kernel_entry NTSTATUS NtQueryInformationProcess(
  [in]            HANDLE           ProcessHandle,
  [in]            PROCESSINFOCLASS ProcessInformationClass,
  [out]           PVOID            ProcessInformation,
  [in]            ULONG            ProcessInformationLength,
  [out, optional] PULONG           ReturnLength
);
C++

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

ProcessInformation 구조체는 다음과 같습니다.

typedef struct _PROCESS_BASIC_INFORMATION {
    NTSTATUS ExitStatus;
    PPEB PebBaseAddress;
    ULONG_PTR AffinityMask;
    KPRIORITY BasePriority;
    ULONG_PTR UniqueProcessId;
    ULONG_PTR InheritedFromUniqueProcessId;
} PROCESS_BASIC_INFORMATION;
C++

코드

부모 프로세스 ID를 구하는 코드는 다음과 같습니다.

#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++
]]>
https://studioys.me/%eb%b6%80%eb%aa%a8-%ed%94%84%eb%a1%9c%ec%84%b8%ec%8a%a4-id-%ea%b5%ac%ed%95%98%ea%b8%b0/feed/ 0