From 481395e1e30d2b9e5ca9296383d334a3b77db14c Mon Sep 17 00:00:00 2001
From: Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Date: Mon, 15 Nov 2021 07:22:49 +0000
Subject: [PATCH v3] Improve PID XXXX is not a PostgreSQL server process
 message

Currently, pg_signal_backend emits generic WARNING "PID XXXX is
not a PostgreSQL server process" for postmaster and auxiliary
processes which doesn't sound sensible. This patch tries to
improve this message.
---
 src/backend/storage/ipc/signalfuncs.c | 38 +++++++++++++++++++++++----
 1 file changed, 33 insertions(+), 5 deletions(-)

diff --git a/src/backend/storage/ipc/signalfuncs.c b/src/backend/storage/ipc/signalfuncs.c
index de69d60e79..f876c2eb21 100644
--- a/src/backend/storage/ipc/signalfuncs.c
+++ b/src/backend/storage/ipc/signalfuncs.c
@@ -48,7 +48,17 @@
 static int
 pg_signal_backend(int pid, int sig)
 {
-	PGPROC	   *proc = BackendPidGetProc(pid);
+	PGPROC	   *proc;
+
+	if (PostmasterPid == pid)
+	{
+		ereport(WARNING,
+				(errmsg("signalling postmaster with PID %d is not allowed", pid)));
+
+		return SIGNAL_BACKEND_ERROR;
+	}
+
+	proc = BackendPidGetProc(pid);
 
 	/*
 	 * BackendPidGetProc returns NULL if the pid isn't valid; but by the time
@@ -61,11 +71,29 @@ pg_signal_backend(int pid, int sig)
 	if (proc == NULL)
 	{
 		/*
-		 * This is just a warning so a loop-through-resultset will not abort
-		 * if one backend terminated on its own during the run.
+		 * AuxiliaryProcs are still PostgreSQL server processes, do a little
+		 * more work and report a proper warning that says we cannot signal
+		 * them.
+		 *
+		 * For an auxiliary process, retrieve process info from AuxiliaryProcs
+		 * stored in shared-memory.
 		 */
-		ereport(WARNING,
-				(errmsg("PID %d is not a PostgreSQL server process", pid)));
+		proc = AuxiliaryPidGetProc(pid);
+
+		if (proc)
+			ereport(WARNING,
+					(errmsg("signalling PostgreSQL server process with PID %d is not allowed",
+							pid)));
+		else
+		{
+			/*
+			 * This is just a warning so a loop-through-resultset will not
+			 * abort if one backend terminated on its own during the run.
+			 */
+			ereport(WARNING,
+					(errmsg("PID %d is not a PostgreSQL server process", pid)));
+		}
+
 		return SIGNAL_BACKEND_ERROR;
 	}
 
-- 
2.25.1

