Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #if _WIN32_WINNT < 0x0500
- # error "should be NT"
- #endif
- #include <windows.h>
- #include <tlhelp32.h>
- #include <winternl.h>
- #include <stdio.h>
- DWORD getppid()
- {
- HANDLE hSnapshot = INVALID_HANDLE_VALUE;
- PROCESSENTRY32 pe32;
- DWORD ppid = 0, pid = GetCurrentProcessId();
- hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
- __try{
- if( hSnapshot == INVALID_HANDLE_VALUE ) __leave;
- ZeroMemory( &pe32, sizeof( pe32 ) );
- pe32.dwSize = sizeof( pe32 );
- if( !Process32First( hSnapshot, &pe32 ) ) __leave;
- do{
- if( pe32.th32ProcessID == pid ){
- ppid = pe32.th32ParentProcessID;
- break;
- }
- }while( Process32Next( hSnapshot, &pe32 ) );
- }
- __finally{
- if( hSnapshot != INVALID_HANDLE_VALUE ) CloseHandle( hSnapshot );
- }
- return ppid;
- }
- DWORD getppid_nt() {
- NTSTATUS status;
- DWORD parent_pid = (DWORD)-1;
- HANDLE process;
- PROCESS_BASIC_INFORMATION pbi;
- ULONG retsize;
- typedef NTSTATUS (__stdcall *DefNtQueryInformationProcess)
- (HANDLE, PROCESSINFOCLASS, PVOID, ULONG, PULONG);
- DefNtQueryInformationProcess NtQueryInformationProcess;
- process = OpenProcess(
- PROCESS_QUERY_INFORMATION,
- FALSE,
- GetCurrentProcessId());
- if (!process)
- return (DWORD)-1;
- NtQueryInformationProcess = (DefNtQueryInformationProcess)
- GetProcAddress(GetModuleHandleA("ntdll"),
- "NtQueryInformationProcess");
- status = NtQueryInformationProcess(
- process,
- ProcessBasicInformation,
- (void*) &pbi,
- sizeof(PROCESS_BASIC_INFORMATION),
- &retsize
- );
- if (!status)
- parent_pid = (DWORD)pbi.Reserved3;
- CloseHandle(process);
- return parent_pid;
- }
- int main(){
- printf( "%lx\n", getppid() );
- printf( "%lx\n", getppid_nt() );
- return 0;
- }
Add Comment
Please, Sign In to add comment