From 4e0359ce93c4b0185c5340d03be505b609417b04 Mon Sep 17 00:00:00 2001 From: Ron Yorston Date: Tue, 14 May 2024 14:03:25 +0100 Subject: ps: report unknown parent PID as 1 If the parent PID doesn't appear in the process table, report it as 1. This more closely matches how orphaned children are handled on UNIX. Adds 96-128 bytes. (GitHub issue #416) --- include/libbb.h | 3 +++ win32/process.c | 22 ++++++++++++++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/include/libbb.h b/include/libbb.h index a7d31ed0c..8d5537114 100644 --- a/include/libbb.h +++ b/include/libbb.h @@ -2148,6 +2148,9 @@ typedef struct procps_status_t { DIR *dir; #else HANDLE snapshot; + unsigned *pids; + int npids; + int maxpids; #endif IF_FEATURE_SHOW_THREADS(DIR *task_dir;) uint8_t shift_pages_to_bytes; diff --git a/win32/process.c b/win32/process.c index b993bb2be..8931eae2e 100644 --- a/win32/process.c +++ b/win32/process.c @@ -583,6 +583,8 @@ static char *get_bb_string(DWORD pid, const char *exe, char *string) return name; } +#define NPIDS 128 + /* POSIX version in libbb/procps.c */ procps_status_t* FAST_FUNC procps_scan(procps_status_t* sp, int flags #if !ENABLE_FEATURE_PS_TIME && !ENABLE_FEATURE_PS_LONG @@ -603,6 +605,8 @@ UNUSED_PARAM free(sp); return NULL; } + sp->pids = xmalloc(sizeof(unsigned) * NPIDS); + sp->maxpids = NPIDS; ret = Process32First(sp->snapshot, &pe); } else { @@ -611,6 +615,7 @@ UNUSED_PARAM if (!ret) { CloseHandle(sp->snapshot); + free(sp->pids); free(sp); return NULL; } @@ -653,8 +658,21 @@ UNUSED_PARAM } } - sp->pid = pe.th32ProcessID; - sp->ppid = pe.th32ParentProcessID; + /* The parent of PID 0 is 0. If the parent is a PID we haven't + * seen set PPID to 1. */ + sp->ppid = pe.th32ProcessID != 0; + for (int i = 0; i < sp->npids; ++i) { + if (sp->pids[i] == pe.th32ParentProcessID) { + sp->ppid = pe.th32ParentProcessID; + break; + } + } + + if (sp->npids == sp->maxpids) { + sp->maxpids += NPIDS; + sp->pids = xrealloc(sp->pids, sizeof(unsigned) * sp->maxpids); + } + sp->pids[sp->npids++] = sp->pid = pe.th32ProcessID; if (sp->pid == getpid()) { comm = applet_name; -- cgit v1.2.3-55-g6feb