Skip to content

Commit

Permalink
win: use NtQueryInformationProcess in uv_os_getppid (libuv#4514)
Browse files Browse the repository at this point in the history
Get parent process ID using NtQueryInformationProcess, it's faster than
using CreateToolhelp32Snapshot.
  • Loading branch information
zuohuiyang authored Aug 26, 2024
1 parent 58dfb6c commit 5cbc82e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 18 deletions.
30 changes: 12 additions & 18 deletions src/win/util.c
Original file line number Diff line number Diff line change
Expand Up @@ -316,25 +316,19 @@ uv_pid_t uv_os_getpid(void) {


uv_pid_t uv_os_getppid(void) {
int parent_pid = -1;
HANDLE handle;
PROCESSENTRY32 pe;
DWORD current_pid = GetCurrentProcessId();

pe.dwSize = sizeof(PROCESSENTRY32);
handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

if (Process32First(handle, &pe)) {
do {
if (pe.th32ProcessID == current_pid) {
parent_pid = pe.th32ParentProcessID;
break;
}
} while( Process32Next(handle, &pe));
NTSTATUS nt_status;
PROCESS_BASIC_INFORMATION basic_info;

nt_status = pNtQueryInformationProcess(GetCurrentProcess(),
ProcessBasicInformation,
&basic_info,
sizeof(basic_info),
NULL);
if (NT_SUCCESS(nt_status)) {
return basic_info.InheritedFromUniqueProcessId;
} else {
return -1;
}

CloseHandle(handle);
return parent_pid;
}


Expand Down
12 changes: 12 additions & 0 deletions src/win/winapi.h
Original file line number Diff line number Diff line change
Expand Up @@ -4458,6 +4458,14 @@ typedef struct _FILE_FS_SECTOR_SIZE_INFORMATION {
ULONG ByteOffsetForPartitionAlignment;
} FILE_FS_SECTOR_SIZE_INFORMATION, *PFILE_FS_SECTOR_SIZE_INFORMATION;

typedef struct _PROCESS_BASIC_INFORMATION {
PVOID Reserved1;
PVOID PebBaseAddress;
PVOID Reserved2[2];
ULONG_PTR UniqueProcessId;
ULONG_PTR InheritedFromUniqueProcessId;
} PROCESS_BASIC_INFORMATION, *PPROCESS_BASIC_INFORMATION;

typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION {
LARGE_INTEGER IdleTime;
LARGE_INTEGER KernelTime;
Expand All @@ -4471,6 +4479,10 @@ typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION {
# define SystemProcessorPerformanceInformation 8
#endif

#ifndef ProcessBasicInformation
# define ProcessBasicInformation 0
#endif

#ifndef ProcessConsoleHostProcess
# define ProcessConsoleHostProcess 49
#endif
Expand Down

0 comments on commit 5cbc82e

Please sign in to comment.