Everything has been started by someone. It is related also to any application executed in operating system, except system itself. If you start notepad from command prompt the parent process of notepad process is command prompt. Currently most of the people find parent process using WMI query. For example:
C:\projects>wmic process get processid,parentprocessid,name | findstr notepad+ notepad++.exe 3928 7096 C:\projects>
|
However it is possible also to get parent process using driver level function NtQuerySystemInformation of Win32 API. It is more complicated but more challenging, because explain process internals in Windows OS. The whole project can be downloaded from here.
NtQuerySystemInformation is not import library function, it is export function from Ntdll.dll. To use it the code should call GetProcAddress function to dynamically link to NtQuerySystemInformation.
typedef DWORD (WINAPI * PNTQUERYSYSYTEMINFORMATION)(DWORD info_class, void *out, DWORD size, DWORD *out_size);
PNTQUERYSYSYTEMINFORMATION pNtQuerySystemInformation = NULL;
...
HANDLE handle = GetModuleHandle(_T("NTDLL.DLL"));
pNtQuerySystemInformation = (PNTQUERYSYSYTEMINFORMATION)GetProcAddress((HMODULE)handle, "NtQuerySystemInformation");
NtQuerySystemInformation get the detailed information of all running processes. This information contains a lot of specific process data including parent process ID.
DWORD status;
ULONG ulReturnLength;
size_t bufferSize = 102400;
psProcessesIni = (PSYSTEM_PROCESSES) malloc (bufferSize);
while (TRUE) {
status = pNtQuerySystemInformation (SystemProcessInformation, (PVOID)psProcessesIni,
bufferSize, &ulReturnLength);
if (status == STATUS_SUCCESS)
break;
else if (status != STATUS_INFO_LENGTH_MISMATCH) { // 0xC0000004L
_tprintf (TEXT("ERROR 0x%X\n"), status);
if(psProcessesIni!=NULL)
free(psProcessesIni);
return 1; // error
}
bufferSize = ulReturnLength;
psProcessesIni = (PSYSTEM_PROCESSES) realloc ((PVOID)psProcessesIni, bufferSize);
}
GetPaternProcess application requited child process ID as an argument, for example:
C:\projects>GetParentProcess.exe 7096 The utility shows the parent process name and Id Current process notepad++.exe (pid=7096) Parent process explorer.exe (pid=3928) C:\projects>
|
A bit more about NtQuerySystemInformation function. For the last 10 years Microsoft threatens to make NtQuerySystemInformation obsolete, however no appropriate alternatives are provided. I suspect it never happens because a lot of Microsoft and third party applications depends on this function.