code_junkie

How can a Win32 process get the pid of its parent?

Nov 11th, 2011
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <windows.h>
  3. #include <tlhelp32.h>
  4.  
  5. int main(int argc, char *argv[])
  6. {
  7. int pid = -1;
  8. HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  9. PROCESSENTRY32 pe = { 0 };
  10. pe.dwSize = sizeof(PROCESSENTRY32);
  11.  
  12. //assume first arg is the PID to get the PPID for, or use own PID
  13. if (argc > 1) {
  14. pid = atoi(argv[1]);
  15. } else {
  16. pid = GetCurrentProcessId();
  17. }
  18.  
  19. if( Process32First(h, &pe)) {
  20. do {
  21. if (pe.th32ProcessID == pid) {
  22. printf("PID: %i; PPID: %in", pid, pe.th32ParentProcessID);
  23. }
  24. } while( Process32Next(h, &pe));
  25. }
  26.  
  27. CloseHandle(h);
  28. }
  29.  
  30. ULONG_PTR GetParentProcessId() // By Napalm @ NetCore2K
  31. {
  32. ULONG_PTR pbi[6];
  33. ULONG ulSize = 0;
  34. LONG (WINAPI *NtQueryInformationProcess)(HANDLE ProcessHandle, ULONG ProcessInformationClass,
  35. PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength);
  36. *(FARPROC *)&NtQueryInformationProcess =
  37. GetProcAddress(LoadLibraryA("NTDLL.DLL"), "NtQueryInformationProcess");
  38. if(NtQueryInformationProcess){
  39. if(NtQueryInformationProcess(GetCurrentProcess(), 0,
  40. &pbi, sizeof(pbi), &ulSize) >= 0 && ulSize == sizeof(pbi))
  41. return pbi[5];
  42. }
  43. return (ULONG_PTR)-1;
  44. }
Add Comment
Please, Sign In to add comment