From 4588cd440e68af132a212d93cd3c4efd73e530b8 Mon Sep 17 00:00:00 2001
From: Ron Yorston <rmy@pobox.com>
Date: Thu, 16 May 2024 12:48:38 +0100
Subject: win32: implement getppid(2)

busybox-w32 had a dummy implementation of getppid(2) which always
returned 1.  Provide a more realistic version.

The effect is limited:

- The PPID shell variable should report a sensible value.

- The special value to omit the parent PID 'pidof -o %PPID'
  should work.

Costs 48 bytes.
---
 include/mingw.h |  2 +-
 win32/process.c | 33 ++++++++++++++++++++++++---------
 2 files changed, 25 insertions(+), 10 deletions(-)

diff --git a/include/mingw.h b/include/mingw.h
index 56a7285e5..2a6cae4ee 100644
--- a/include/mingw.h
+++ b/include/mingw.h
@@ -477,7 +477,7 @@ int getuid(void);
 #define geteuid getuid
 #define getegid getuid
 int getgroups(int n, gid_t *groups);
-IMPL(getppid,int,1,void);
+pid_t getppid(void);
 NOIMPL(getsid,pid_t pid UNUSED_PARAM);
 int getlogin_r(char *buf, size_t len);
 int fcntl(int fd, int cmd, ...);
diff --git a/win32/process.c b/win32/process.c
index bbb04678f..bf98ef746 100644
--- a/win32/process.c
+++ b/win32/process.c
@@ -583,6 +583,19 @@ static char *get_bb_string(DWORD pid, const char *exe, char *string)
 	return name;
 }
 
+pid_t getppid(void)
+{
+	procps_status_t *sp = NULL;
+	int my_pid = getpid();
+
+	while ((sp = procps_scan(sp, 0)) != NULL) {
+		if (sp->pid == my_pid) {
+			return sp->ppid;
+		}
+	}
+	return 1;
+}
+
 #define NPIDS 128
 
 /* POSIX version in libbb/procps.c */
@@ -677,16 +690,18 @@ UNUSED_PARAM
 	}
 	sp->pid = pe.th32ProcessID;
 
-	if (sp->pid == getpid()) {
-		comm = applet_name;
-	}
-	else if ((name=get_bb_string(sp->pid, pe.szExeFile, bb_comm)) != NULL) {
-		comm = name;
-	}
-	else {
-		comm = pe.szExeFile;
+	if (flags & PSSCAN_COMM) {
+		if (sp->pid == getpid()) {
+			comm = applet_name;
+		}
+		else if ((name=get_bb_string(sp->pid, pe.szExeFile, bb_comm)) != NULL) {
+			comm = name;
+		}
+		else {
+			comm = pe.szExeFile;
+		}
+		safe_strncpy(sp->comm, comm, COMM_LEN);
 	}
-	safe_strncpy(sp->comm, comm, COMM_LEN);
 
 	return sp;
 }
-- 
cgit v1.2.3-55-g6feb