pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
Add errdetail() with PID and UID about source of termination signal
54+ messages / 10 participants
[nested] [flat]

* Add errdetail() with PID and UID about source of termination signal
@ 2026-02-18 07:32  Jakub Wartak <jakub.wartak@enterprisedb.com>
  0 siblings, 1 reply; 54+ messages in thread

From: Jakub Wartak @ 2026-02-18 07:32 UTC (permalink / raw)
  To: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi all,

From time to time we have scenario where somebody has some backend killed by
some_script_somewhere(TM) in a multi-department company scenario and
to me it was
always unnecessary time intensive to identify the origin of the signal.

eBPF/bpftrace can be used to find the origin, but I think that PG could
simply log which PID/UID (e.g. root or pg-user) raised the signal. So Linux
has SA_SIGINFO, we could use that to provide mentioned things. As expected,
search of course returned that it was discussed earlier here [1] 11 years ago,
but there was no patch back then, so attached is an attempt to do just that.

No GUC, and yes it only displays it on Linux. I think FreeBSD also has
this, but I
haven't tried it there (or I haven't tried other OSes without it -
proper autoconf/meson
sa_sigaction SA_SIGINFO detection  is probably missing with proper
#ifdefs ), but I
would first like to learn if that would be a welcomed feature or not.

-J.

[1] - https://hackorum.dev/topics/32019

Attachments:

  [text/x-patch] v1-0001-Add-errdetail-with-PID-and-UID-about-source-of-te.patch (10.6K, ../../CAKZiRmyrOWovZSdixpLd3PGMQXuQL_zw2Ght5XhHCkQ1uDsxjw@mail.gmail.com/2-v1-0001-Add-errdetail-with-PID-and-UID-about-source-of-te.patch)
  download | inline diff:
From 28fe83686c4031eebd1ffad2487aef0101a05295 Mon Sep 17 00:00:00 2001
From: Jakub Wartak <jakub.wartak@enterprisedb.com>
Date: Tue, 17 Feb 2026 12:41:01 +0100
Subject: [PATCH v1] Add errdetail() with PID and UID about source of
 termination signal.

On Linux we can use SA_SIGINFO to fetch additional information about sender
of the signal, which can aid troubleshooting. Sample log:
  FATAL:  terminating connection due to administrator command
  DETAIL:  signal sent by PID 508477, UID 1000.

Author: Jakub Wartak <jakub.wartak@enterprisedb.com>
Reviewed-by:
Discussion:
---
 src/backend/postmaster/bgworker.c |  6 ++++-
 src/backend/replication/syncrep.c | 12 +++++++--
 src/backend/tcop/postgres.c       | 42 +++++++++++++++++++++++++------
 src/backend/utils/init/globals.c  |  2 ++
 src/bin/psql/t/001_basic.pl       |  7 +++---
 src/include/miscadmin.h           |  2 ++
 src/port/pqsignal.c               | 36 +++++++++++++++++++++++---
 7 files changed, 90 insertions(+), 17 deletions(-)

diff --git a/src/backend/postmaster/bgworker.c b/src/backend/postmaster/bgworker.c
index 261ccd3f59..20b1893533 100644
--- a/src/backend/postmaster/bgworker.c
+++ b/src/backend/postmaster/bgworker.c
@@ -729,7 +729,11 @@ bgworker_die(SIGNAL_ARGS)
 	ereport(FATAL,
 			(errcode(ERRCODE_ADMIN_SHUTDOWN),
 			 errmsg("terminating background worker \"%s\" due to administrator command",
-					MyBgworkerEntry->bgw_type)));
+					MyBgworkerEntry->bgw_type),
+			proc_die_sender_pid == 0 ? 0 :
+				errdetail("signal sent by PID %d, UID %d.",
+					proc_die_sender_pid, proc_die_sender_uid)
+			));
 }
 
 /*
diff --git a/src/backend/replication/syncrep.c b/src/backend/replication/syncrep.c
index 7ea6001e9a..339c03fb6a 100644
--- a/src/backend/replication/syncrep.c
+++ b/src/backend/replication/syncrep.c
@@ -302,7 +302,11 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 			ereport(WARNING,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
 					 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
+					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby."),
+						proc_die_sender_pid == 0 ? 0 :
+							errdetail("signal sent by PID %d, UID %d.",
+								proc_die_sender_pid, proc_die_sender_uid)
+						));
 			whereToSendOutput = DestNone;
 			SyncRepCancelWait();
 			break;
@@ -319,7 +323,11 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 			QueryCancelPending = false;
 			ereport(WARNING,
 					(errmsg("canceling wait for synchronous replication due to user request"),
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
+					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby."),
+						proc_die_sender_pid == 0 ? 0 :
+							errdetail("signal sent by PID %d, UID %d.",
+								proc_die_sender_pid, proc_die_sender_uid)
+						));
 			SyncRepCancelWait();
 			break;
 		}
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 21de158adb..115ea965d4 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -3357,15 +3357,27 @@ ProcessInterrupts(void)
 		else if (AmAutoVacuumWorkerProcess())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating autovacuum process due to administrator command")));
+					 errmsg("terminating autovacuum process due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 		else if (IsLogicalWorker())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating logical replication worker due to administrator command")));
+					 errmsg("terminating logical replication worker due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 		else if (IsLogicalLauncher())
 		{
 			ereport(DEBUG1,
-					(errmsg_internal("logical replication launcher shutting down")));
+					(errmsg_internal("logical replication launcher shutting down"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 
 			/*
 			 * The logical replication launcher can be stopped at any time.
@@ -3376,23 +3388,39 @@ ProcessInterrupts(void)
 		else if (AmWalReceiverProcess())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating walreceiver process due to administrator command")));
+					 errmsg("terminating walreceiver process due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 		else if (AmBackgroundWorkerProcess())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
 					 errmsg("terminating background worker \"%s\" due to administrator command",
-							MyBgworkerEntry->bgw_type)));
+							MyBgworkerEntry->bgw_type),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 		else if (AmIoWorkerProcess())
 		{
 			ereport(DEBUG1,
-					(errmsg_internal("io worker shutting down due to administrator command")));
+					(errmsg_internal("io worker shutting down due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 
 			proc_exit(0);
 		}
 		else
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating connection due to administrator command")));
+					 errmsg("terminating connection due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 	}
 
 	if (CheckClientConnectionPending)
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 36ad708b36..144c8aca1b 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -32,6 +32,8 @@ ProtocolVersion FrontendProtocol;
 volatile sig_atomic_t InterruptPending = false;
 volatile sig_atomic_t QueryCancelPending = false;
 volatile sig_atomic_t ProcDiePending = false;
+volatile sig_atomic_t proc_die_sender_pid = 0;
+volatile sig_atomic_t proc_die_sender_uid = 0;
 volatile sig_atomic_t CheckClientConnectionPending = false;
 volatile sig_atomic_t ClientConnectionLost = false;
 volatile sig_atomic_t IdleInTransactionSessionTimeoutPending = false;
diff --git a/src/bin/psql/t/001_basic.pl b/src/bin/psql/t/001_basic.pl
index 6839f27cbe..aa8f819d9d 100644
--- a/src/bin/psql/t/001_basic.pl
+++ b/src/bin/psql/t/001_basic.pl
@@ -142,12 +142,11 @@ my ($ret, $out, $err) = $node->psql('postgres',
 is($ret, 2, 'server crash: psql exit code');
 like($out, qr/before/, 'server crash: output before crash');
 unlike($out, qr/AFTER/, 'server crash: no output after crash');
-is( $err,
-	'psql:<stdin>:2: FATAL:  terminating connection due to administrator command
-psql:<stdin>:2: server closed the connection unexpectedly
+like( $err, qr/psql:<stdin>:2: FATAL:  terminating connection due to administrator command
+(?:DETAIL:  signal sent by PID \d+, UID \d+.\n)?psql:<stdin>:2: server closed the connection unexpectedly
 	This probably means the server terminated abnormally
 	before or while processing the request.
-psql:<stdin>:2: error: connection to server was lost',
+psql:<stdin>:2: error: connection to server was lost/,
 	'server crash: error message');
 
 # test \errverbose
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index f16f35659b..63256eff84 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -90,6 +90,8 @@
 extern PGDLLIMPORT volatile sig_atomic_t InterruptPending;
 extern PGDLLIMPORT volatile sig_atomic_t QueryCancelPending;
 extern PGDLLIMPORT volatile sig_atomic_t ProcDiePending;
+extern PGDLLIMPORT volatile sig_atomic_t proc_die_sender_pid;
+extern PGDLLIMPORT volatile sig_atomic_t proc_die_sender_uid;
 extern PGDLLIMPORT volatile sig_atomic_t IdleInTransactionSessionTimeoutPending;
 extern PGDLLIMPORT volatile sig_atomic_t TransactionTimeoutPending;
 extern PGDLLIMPORT volatile sig_atomic_t IdleSessionTimeoutPending;
diff --git a/src/port/pqsignal.c b/src/port/pqsignal.c
index fbdf9341c2..bb632285f4 100644
--- a/src/port/pqsignal.c
+++ b/src/port/pqsignal.c
@@ -82,10 +82,18 @@ static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
  *
  * This wrapper also handles restoring the value of errno.
  */
+#if !defined(FRONTEND) && !defined(WIN32)
+static void
+wrapper_handler(int signo, siginfo_t *info, void *context)
+#else
 static void
 wrapper_handler(SIGNAL_ARGS)
+#endif
 {
 	int			save_errno = errno;
+#if !defined(FRONTEND) && !defined(WIN32)
+	int			postgres_signal_arg = signo;
+#endif
 
 	Assert(postgres_signal_arg > 0);
 	Assert(postgres_signal_arg < PG_NSIG);
@@ -105,6 +113,14 @@ wrapper_handler(SIGNAL_ARGS)
 		raise(postgres_signal_arg);
 		return;
 	}
+
+#ifndef WIN32
+	if (signo == SIGTERM && info)
+	{
+		proc_die_sender_pid = info->si_pid;
+		proc_die_sender_uid = info->si_uid;
+	}
+#endif
 #endif
 
 	(*pqsignal_handlers[postgres_signal_arg]) (postgres_signal_arg);
@@ -125,6 +141,7 @@ pqsignal(int signo, pqsigfunc func)
 #if !(defined(WIN32) && defined(FRONTEND))
 	struct sigaction act;
 #endif
+	bool		use_wrapper = false;
 
 	Assert(signo > 0);
 	Assert(signo < PG_NSIG);
@@ -132,13 +149,26 @@ pqsignal(int signo, pqsigfunc func)
 	if (func != SIG_IGN && func != SIG_DFL)
 	{
 		pqsignal_handlers[signo] = func;	/* assumed atomic */
-		func = wrapper_handler;
+		use_wrapper = true;
 	}
 
 #if !(defined(WIN32) && defined(FRONTEND))
-	act.sa_handler = func;
 	sigemptyset(&act.sa_mask);
 	act.sa_flags = SA_RESTART;
+#if !defined(FRONTEND) && !defined(WIN32)
+	if (use_wrapper)
+	{
+		act.sa_sigaction = wrapper_handler;
+		act.sa_flags |= SA_SIGINFO;
+	}
+	else
+	{
+		act.sa_handler = func;
+	}
+#else
+	act.sa_handler = use_wrapper ? wrapper_handler : func;
+#endif
+
 #ifdef SA_NOCLDSTOP
 	if (signo == SIGCHLD)
 		act.sa_flags |= SA_NOCLDSTOP;
@@ -147,7 +177,7 @@ pqsignal(int signo, pqsigfunc func)
 		Assert(false);			/* probably indicates coding error */
 #else
 	/* Forward to Windows native signal system. */
-	if (signal(signo, func) == SIG_ERR)
+	if (signal(signo, use_wrapper ? wrapper_handler : func) == SIG_ERR)
 		Assert(false);			/* probably indicates coding error */
 #endif
 }
-- 
2.43.0



^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-02-18 16:08  Jim Jones <jim.jones@uni-muenster.de>
  parent: Jakub Wartak <jakub.wartak@enterprisedb.com>
  0 siblings, 1 reply; 54+ messages in thread

From: Jim Jones @ 2026-02-18 16:08 UTC (permalink / raw)
  To: Jakub Wartak <jakub.wartak@enterprisedb.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi Jakub

On 18/02/2026 08:32, Jakub Wartak wrote:
> I would first like to learn if that would be a welcomed feature or not.

+1

I think it's a very useful feature (only tested on Linux)

FATAL:  terminating connection due to administrator command
DETAIL:  signal sent by PID 1592705, UID 1000.

I'm wondering if there is a standard style for displaying such values in
DETAIL. For instance, the checkpoint LOG is formatted like this:

LOG:  checkpoint complete: ... write=0.044 s, sync=0.071 s, ...

I'm not sure if it applies for DETAIL, but at least it's what the
example at the error style guide[1] suggests:

Detail:     Failed syscall was shmget(key=%d, size=%u, 0%o).

Thanks!

Best, Jim


1 - https://www.postgresql.org/docs/current/error-style-guide.html





^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-02-23 13:28  Jakub Wartak <jakub.wartak@enterprisedb.com>
  parent: Jim Jones <jim.jones@uni-muenster.de>
  0 siblings, 1 reply; 54+ messages in thread

From: Jakub Wartak @ 2026-02-23 13:28 UTC (permalink / raw)
  To: Jim Jones <jim.jones@uni-muenster.de>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Wed, Feb 18, 2026 at 5:08 PM Jim Jones <jim.jones@uni-muenster.de> wrote:
>
> Hi Jakub
>
> On 18/02/2026 08:32, Jakub Wartak wrote:
> > I would first like to learn if that would be a welcomed feature or not.
>
> +1
>
> I think it's a very useful feature (only tested on Linux)
>
> FATAL:  terminating connection due to administrator command
> DETAIL:  signal sent by PID 1592705, UID 1000.

Hi Jim, thanks for feedback :)

> I'm wondering if there is a standard style for displaying such values in
> DETAIL. For instance, the checkpoint LOG is formatted like this:
>
> LOG:  checkpoint complete: ... write=0.044 s, sync=0.071 s, ...
>
> I'm not sure if it applies for DETAIL, but at least it's what the
> example at the error style guide[1] suggests:
>
> Detail:     Failed syscall was shmget(key=%d, size=%u, 0%o).

After using `grep -hr errdetail src/ | sed -E 's/^\s+//g' | sort |
uniq` I doubt there is any
real standard, but one can find there:

errdetail("The server process with PID %d is among those with the
   oldest transactions.", minPid)
errdetail("The source process with PID %d is not running anymore.",

One could say that all those DETAIL log messages should start with an
 uppercase letter, yet it didn't look good to me when above
   "terminating connection ..."
started itself with a lowercase letter "t", and then next-line DETAIL
we would start
with an uppercase
  "Signal..".

but, I'm open to any better proposal...

-J.





^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-02-24 08:39  Chao Li <li.evan.chao@gmail.com>
  parent: Jakub Wartak <jakub.wartak@enterprisedb.com>
  0 siblings, 1 reply; 54+ messages in thread

From: Chao Li @ 2026-02-24 08:39 UTC (permalink / raw)
  To: Jakub Wartak <jakub.wartak@enterprisedb.com>; +Cc: Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>



> On Feb 23, 2026, at 21:28, Jakub Wartak <jakub.wartak@enterprisedb.com> wrote:
> 
> On Wed, Feb 18, 2026 at 5:08 PM Jim Jones <jim.jones@uni-muenster.de> wrote:
>> 
>> Hi Jakub
>> 
>> On 18/02/2026 08:32, Jakub Wartak wrote:
>>> I would first like to learn if that would be a welcomed feature or not.
>> 
>> +1
>> 
>> I think it's a very useful feature (only tested on Linux)
>> 
>> FATAL:  terminating connection due to administrator command
>> DETAIL:  signal sent by PID 1592705, UID 1000.
> 
> Hi Jim, thanks for feedback :)
> 
>> I'm wondering if there is a standard style for displaying such values in
>> DETAIL. For instance, the checkpoint LOG is formatted like this:
>> 
>> LOG:  checkpoint complete: ... write=0.044 s, sync=0.071 s, ...
>> 
>> I'm not sure if it applies for DETAIL, but at least it's what the
>> example at the error style guide[1] suggests:
>> 
>> Detail:     Failed syscall was shmget(key=%d, size=%u, 0%o).
> 
> After using `grep -hr errdetail src/ | sed -E 's/^\s+//g' | sort |
> uniq` I doubt there is any
> real standard, but one can find there:
> 
> errdetail("The server process with PID %d is among those with the
>   oldest transactions.", minPid)
> errdetail("The source process with PID %d is not running anymore.",
> 
> One could say that all those DETAIL log messages should start with an
> uppercase letter, yet it didn't look good to me when above
>   "terminating connection ..."
> started itself with a lowercase letter "t", and then next-line DETAIL
> we would start
> with an uppercase
>  "Signal..".
> 
> but, I'm open to any better proposal...
> 
> -J.

There is guidance in the documentation regarding error message style: https://www.postgresql.org/docs/current/error-style-guide.html
```
Detail and hint messages: Use complete sentences, and end each with a period. Capitalize the first word of sentences. Put two spaces after the period if another sentence follows (for English text; might be inappropriate in other languages).
```

I also noticed that some existing DETAIL and HINT messages do not fully follow this guideline. But I believe new code should adhere to the documented style as much as possible. In particular, DETAIL and HINT messages should begin with a capital letter and follow the complete-sentence convention.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/









^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-02-24 10:05  Jakub Wartak <jakub.wartak@enterprisedb.com>
  parent: Chao Li <li.evan.chao@gmail.com>
  0 siblings, 1 reply; 54+ messages in thread

From: Jakub Wartak @ 2026-02-24 10:05 UTC (permalink / raw)
  To: Chao Li <li.evan.chao@gmail.com>; +Cc: Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, Feb 24, 2026 at 9:40 AM Chao Li <li.evan.chao@gmail.com> wrote:
[..]

> There is guidance in the documentation regarding error message style: https://www.postgresql.org/docs/current/error-style-guide.html
> ```
> Detail and hint messages: Use complete sentences, and end each with a period. Capitalize the first word of sentences. Put two spaces after the period if another sentence follows (for English text; might be inappropriate in other languages).
> ```
>
> I also noticed that some existing DETAIL and HINT messages do not fully follow this guideline. But I believe new code should adhere to the documented style as much as possible. In particular, DETAIL and HINT messages should begin with a capital letter and follow the complete-sentence convention.

Hi, v2 attached, WIP, the only known remaining issue to me is that
windows might fail to compile as it probably doesn't have concept of
uid_t... I'm wondering what to do there.

1. Rebased due to recent change to remove bgwriter_die()
2. Added auto-detection of SA_SIGINFO to meson and autoconf
3. Changed "Signal" to be in upper case now (I don't like it, but it
follows guideline now)
4. Tested on FreeBSD 14.3 - it works there too now..
5. ...and fixed some clang warnings by changing %d -> %lld in
errdetail due to apparent pid_t differences on platforms.

-J.

Attachments:

  [text/x-patch] v2-0001-Add-errdetail-with-PID-and-UID-about-source-of-te.patch (13.5K, ../../CAKZiRmxrS=--uSO_zGoaVhu2Wq8heh-3sYQKriSA_MiZZn_DfQ@mail.gmail.com/2-v2-0001-Add-errdetail-with-PID-and-UID-about-source-of-te.patch)
  download | inline diff:
From 0d0bb30bd7f785a1efda3c3aa69cd5d3d8a98885 Mon Sep 17 00:00:00 2001
From: Jakub Wartak <jakub.wartak@enterprisedb.com>
Date: Tue, 17 Feb 2026 12:41:01 +0100
Subject: [PATCH v2] Add errdetail() with PID and UID about source of
 termination signal.

On Linux and FreeBSD we can use SA_SIGINFO to fetch additional information
about sender of the signal, which can aid troubleshooting. Sample log:
  FATAL:  terminating connection due to administrator command
  DETAIL:  Signal sent by PID 508477, UID 1000.

Author: Jakub Wartak <jakub.wartak@enterprisedb.com>
Reviewed-by: Jim Jones <jim.jones@uni-muenster.de>
Discussion: https://www.postgresql.org/message-id/CAKZiRmyrOWovZSdixpLd3PGMQXuQL_zw2Ght5XhHCkQ1uDsxjw%40mail.gmail.com
---
 configure                         | 42 +++++++++++++++++++++++++++++++
 configure.ac                      | 18 +++++++++++++
 meson.build                       |  4 +++
 src/backend/replication/syncrep.c | 12 +++++++--
 src/backend/tcop/postgres.c       | 42 +++++++++++++++++++++++++------
 src/backend/utils/init/globals.c  |  2 ++
 src/bin/psql/t/001_basic.pl       |  7 +++---
 src/include/miscadmin.h           |  2 ++
 src/include/pg_config.h.in        |  3 +++
 src/port/pqsignal.c               | 35 +++++++++++++++++++++++---
 10 files changed, 151 insertions(+), 16 deletions(-)

diff --git a/configure b/configure
index a285a6ec3d7..704c88aee3d 100755
--- a/configure
+++ b/configure
@@ -15693,6 +15693,48 @@ if test "$ac_cv_sizeof_off_t" -lt 8; then
   fi
 fi
 
+# Check for SA_SIGINFO extended signal handler availability
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for SA_SIGINFO" >&5
+$as_echo_n "checking for SA_SIGINFO... " >&6; }
+if ${ac_cv_have_sa_siginfo+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+
+    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+
+            #include <signal.h>
+            #include <stddef.h>
+
+int
+main ()
+{
+
+            struct sigaction sa;
+            sa.sa_flags = SA_SIGINFO;
+
+  ;
+  return 0;
+}
+
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_have_sa_siginfo=yes
+else
+  ac_cv_have_sa_siginfo=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_have_sa_siginfo" >&5
+$as_echo "$ac_cv_have_sa_siginfo" >&6; }
+
+if test "x$ac_cv_have_sa_siginfo" = "xyes"; then
+
+$as_echo "#define HAVE_SA_SIGINFO 1" >>confdefs.h
+
+fi
 
 ##
 ## Functions, global variables
diff --git a/configure.ac b/configure.ac
index 476a76c7991..183bc992126 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1822,6 +1822,24 @@ if test "$ac_cv_sizeof_off_t" -lt 8; then
   fi
 fi
 
+# Check for SA_SIGINFO extended signal handler availability
+AC_CACHE_CHECK([for SA_SIGINFO], [ac_cv_have_sa_siginfo], [
+    AC_COMPILE_IFELSE([
+        AC_LANG_PROGRAM([[
+            #include <signal.h>
+            #include <stddef.h>
+        ]], [[
+            struct sigaction sa;
+            sa.sa_flags = SA_SIGINFO;
+        ]])
+    ],
+    [ac_cv_have_sa_siginfo=yes],
+    [ac_cv_have_sa_siginfo=no])
+])
+
+if test "x$ac_cv_have_sa_siginfo" = "xyes"; then
+    AC_DEFINE([HAVE_SA_SIGINFO], 1, [Define to 1 if you have SA_SIGINFO available.])
+fi
 
 ##
 ## Functions, global variables
diff --git a/meson.build b/meson.build
index 5122706477d..3aa675e7ebb 100644
--- a/meson.build
+++ b/meson.build
@@ -2879,6 +2879,10 @@ if cc.has_member('struct sockaddr', 'sa_len',
   cdata.set('HAVE_STRUCT_SOCKADDR_SA_LEN', 1)
 endif
 
+if cc.has_header_symbol('signal.h', 'SA_SIGINFO')
+  cdata.set('HAVE_SA_SIGINFO', 1)
+endif
+
 if cc.has_member('struct tm', 'tm_zone',
     args: test_c_args, include_directories: postgres_inc,
     prefix: '''
diff --git a/src/backend/replication/syncrep.c b/src/backend/replication/syncrep.c
index d1582a5d711..74cd41adfd4 100644
--- a/src/backend/replication/syncrep.c
+++ b/src/backend/replication/syncrep.c
@@ -302,7 +302,11 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 			ereport(WARNING,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
 					 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
+					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby."),
+						proc_die_sender_pid == 0 ? 0 :
+							errdetail("Signal sent by PID %lld, UID %lld.",
+								(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+						));
 			whereToSendOutput = DestNone;
 			SyncRepCancelWait();
 			break;
@@ -319,7 +323,11 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 			QueryCancelPending = false;
 			ereport(WARNING,
 					(errmsg("canceling wait for synchronous replication due to user request"),
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
+					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby."),
+						proc_die_sender_pid == 0 ? 0 :
+							errdetail("Signal sent by PID %lld, UID %lld.",
+								(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+						));
 			SyncRepCancelWait();
 			break;
 		}
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index d01a09dd0c4..6e3a0ec8655 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -3357,15 +3357,27 @@ ProcessInterrupts(void)
 		else if (AmAutoVacuumWorkerProcess())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating autovacuum process due to administrator command")));
+					 errmsg("terminating autovacuum process due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %lld, UID %lld.",
+							(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+					));
 		else if (IsLogicalWorker())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating logical replication worker due to administrator command")));
+					 errmsg("terminating logical replication worker due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %lld, UID %lld.",
+							(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+					));
 		else if (IsLogicalLauncher())
 		{
 			ereport(DEBUG1,
-					(errmsg_internal("logical replication launcher shutting down")));
+					(errmsg_internal("logical replication launcher shutting down"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %lld, UID %lld.",
+							(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+					));
 
 			/*
 			 * The logical replication launcher can be stopped at any time.
@@ -3376,23 +3388,39 @@ ProcessInterrupts(void)
 		else if (AmWalReceiverProcess())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating walreceiver process due to administrator command")));
+					 errmsg("terminating walreceiver process due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %lld, UID %lld.",
+							(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+					));
 		else if (AmBackgroundWorkerProcess())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
 					 errmsg("terminating background worker \"%s\" due to administrator command",
-							MyBgworkerEntry->bgw_type)));
+							MyBgworkerEntry->bgw_type),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %lld, UID %lld.",
+							(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+					));
 		else if (AmIoWorkerProcess())
 		{
 			ereport(DEBUG1,
-					(errmsg_internal("io worker shutting down due to administrator command")));
+					(errmsg_internal("io worker shutting down due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %lld, UID %lld.",
+							(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+					));
 
 			proc_exit(0);
 		}
 		else
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating connection due to administrator command")));
+					 errmsg("terminating connection due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %lld, UID %lld.",
+							(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+					));
 	}
 
 	if (CheckClientConnectionPending)
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 36ad708b360..1cd1afa8be5 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -32,6 +32,8 @@ ProtocolVersion FrontendProtocol;
 volatile sig_atomic_t InterruptPending = false;
 volatile sig_atomic_t QueryCancelPending = false;
 volatile sig_atomic_t ProcDiePending = false;
+volatile pid_t proc_die_sender_pid = 0;
+volatile uid_t proc_die_sender_uid = 0;
 volatile sig_atomic_t CheckClientConnectionPending = false;
 volatile sig_atomic_t ClientConnectionLost = false;
 volatile sig_atomic_t IdleInTransactionSessionTimeoutPending = false;
diff --git a/src/bin/psql/t/001_basic.pl b/src/bin/psql/t/001_basic.pl
index 6839f27cbe5..7bd585d40e3 100644
--- a/src/bin/psql/t/001_basic.pl
+++ b/src/bin/psql/t/001_basic.pl
@@ -142,12 +142,11 @@ my ($ret, $out, $err) = $node->psql('postgres',
 is($ret, 2, 'server crash: psql exit code');
 like($out, qr/before/, 'server crash: output before crash');
 unlike($out, qr/AFTER/, 'server crash: no output after crash');
-is( $err,
-	'psql:<stdin>:2: FATAL:  terminating connection due to administrator command
-psql:<stdin>:2: server closed the connection unexpectedly
+like( $err, qr/psql:<stdin>:2: FATAL:  terminating connection due to administrator command
+(?:DETAIL:  Signal sent by PID \d+, UID \d+.\n)?psql:<stdin>:2: server closed the connection unexpectedly
 	This probably means the server terminated abnormally
 	before or while processing the request.
-psql:<stdin>:2: error: connection to server was lost',
+psql:<stdin>:2: error: connection to server was lost/,
 	'server crash: error message');
 
 # test \errverbose
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index f16f35659b9..eef6e576b20 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -90,6 +90,8 @@
 extern PGDLLIMPORT volatile sig_atomic_t InterruptPending;
 extern PGDLLIMPORT volatile sig_atomic_t QueryCancelPending;
 extern PGDLLIMPORT volatile sig_atomic_t ProcDiePending;
+extern PGDLLIMPORT volatile pid_t proc_die_sender_pid;
+extern PGDLLIMPORT volatile uid_t proc_die_sender_uid;
 extern PGDLLIMPORT volatile sig_atomic_t IdleInTransactionSessionTimeoutPending;
 extern PGDLLIMPORT volatile sig_atomic_t TransactionTimeoutPending;
 extern PGDLLIMPORT volatile sig_atomic_t IdleSessionTimeoutPending;
diff --git a/src/include/pg_config.h.in b/src/include/pg_config.h.in
index a0bd84376e7..1fbb2ce380a 100644
--- a/src/include/pg_config.h.in
+++ b/src/include/pg_config.h.in
@@ -340,6 +340,9 @@
 /* Define to 1 if you have the `rl_variable_bind' function. */
 #undef HAVE_RL_VARIABLE_BIND
 
+/* Define to 1 if you have SA_SIGINFO available. */
+#undef HAVE_SA_SIGINFO
+
 /* Define to 1 if you have the <security/pam_appl.h> header file. */
 #undef HAVE_SECURITY_PAM_APPL_H
 
diff --git a/src/port/pqsignal.c b/src/port/pqsignal.c
index fbdf9341c2f..5e61739fdc3 100644
--- a/src/port/pqsignal.c
+++ b/src/port/pqsignal.c
@@ -82,10 +82,19 @@ static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
  *
  * This wrapper also handles restoring the value of errno.
  */
+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+static void
+wrapper_handler(int signo, siginfo_t *info, void *context)
+#else
 static void
 wrapper_handler(SIGNAL_ARGS)
+#endif
 {
 	int			save_errno = errno;
+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+	/* SIGNAL_ARGS defines postgres_signal_arg */
+	int			postgres_signal_arg = signo;
+#endif
 
 	Assert(postgres_signal_arg > 0);
 	Assert(postgres_signal_arg < PG_NSIG);
@@ -105,6 +114,14 @@ wrapper_handler(SIGNAL_ARGS)
 		raise(postgres_signal_arg);
 		return;
 	}
+
+#ifdef HAVE_SA_SIGINFO
+	if (signo == SIGTERM && info)
+	{
+		proc_die_sender_pid = info->si_pid;
+		proc_die_sender_uid = info->si_uid;
+	}
+#endif
 #endif
 
 	(*pqsignal_handlers[postgres_signal_arg]) (postgres_signal_arg);
@@ -125,6 +142,7 @@ pqsignal(int signo, pqsigfunc func)
 #if !(defined(WIN32) && defined(FRONTEND))
 	struct sigaction act;
 #endif
+	bool		use_wrapper = false;
 
 	Assert(signo > 0);
 	Assert(signo < PG_NSIG);
@@ -132,13 +150,24 @@ pqsignal(int signo, pqsigfunc func)
 	if (func != SIG_IGN && func != SIG_DFL)
 	{
 		pqsignal_handlers[signo] = func;	/* assumed atomic */
-		func = wrapper_handler;
+		use_wrapper = true;
 	}
 
 #if !(defined(WIN32) && defined(FRONTEND))
-	act.sa_handler = func;
 	sigemptyset(&act.sa_mask);
 	act.sa_flags = SA_RESTART;
+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+	if (use_wrapper)
+	{
+		act.sa_sigaction = wrapper_handler;
+		act.sa_flags |= SA_SIGINFO;
+	}
+	else
+		act.sa_handler = func;
+#else
+	act.sa_handler = use_wrapper ? wrapper_handler : func;
+#endif
+
 #ifdef SA_NOCLDSTOP
 	if (signo == SIGCHLD)
 		act.sa_flags |= SA_NOCLDSTOP;
@@ -147,7 +176,7 @@ pqsignal(int signo, pqsigfunc func)
 		Assert(false);			/* probably indicates coding error */
 #else
 	/* Forward to Windows native signal system. */
-	if (signal(signo, func) == SIG_ERR)
+	if (signal(signo, use_wrapper ? wrapper_handler : func) == SIG_ERR)
 		Assert(false);			/* probably indicates coding error */
 #endif
 }
-- 
2.43.0



^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-02-24 16:15  Andrew Dunstan <andrew@dunslane.net>
  parent: Jakub Wartak <jakub.wartak@enterprisedb.com>
  0 siblings, 1 reply; 54+ messages in thread

From: Andrew Dunstan @ 2026-02-24 16:15 UTC (permalink / raw)
  To: Jakub Wartak <jakub.wartak@enterprisedb.com>; Chao Li <li.evan.chao@gmail.com>; +Cc: Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>


On 2026-02-24 Tu 5:05 AM, Jakub Wartak wrote:
> On Tue, Feb 24, 2026 at 9:40 AM Chao Li <li.evan.chao@gmail.com> wrote:
> [..]
>
>> There is guidance in the documentation regarding error message style: https://www.postgresql.org/docs/current/error-style-guide.html
>> ```
>> Detail and hint messages: Use complete sentences, and end each with a period. Capitalize the first word of sentences. Put two spaces after the period if another sentence follows (for English text; might be inappropriate in other languages).
>> ```
>>
>> I also noticed that some existing DETAIL and HINT messages do not fully follow this guideline. But I believe new code should adhere to the documented style as much as possible. In particular, DETAIL and HINT messages should begin with a capital letter and follow the complete-sentence convention.
> Hi, v2 attached, WIP, the only known remaining issue to me is that
> windows might fail to compile as it probably doesn't have concept of
> uid_t... I'm wondering what to do there.


I don't think it will arise, as Windows doesn't have the siginfo stuff, 
AFAIK.


cheers


andrew

--
Andrew Dunstan
EDB: https://www.enterprisedb.com






^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-02-25 08:26  Jakub Wartak <jakub.wartak@enterprisedb.com>
  parent: Andrew Dunstan <andrew@dunslane.net>
  0 siblings, 1 reply; 54+ messages in thread

From: Jakub Wartak @ 2026-02-25 08:26 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Chao Li <li.evan.chao@gmail.com>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, Feb 24, 2026 at 5:15 PM Andrew Dunstan <andrew@dunslane.net> wrote:
>
>
> On 2026-02-24 Tu 5:05 AM, Jakub Wartak wrote:
> > On Tue, Feb 24, 2026 at 9:40 AM Chao Li <li.evan.chao@gmail.com> wrote:
> > [..]
> >
> >> There is guidance in the documentation regarding error message style: https://www.postgresql.org/docs/current/error-style-guide.html
> >> ```
> >> Detail and hint messages: Use complete sentences, and end each with a period. Capitalize the first word of sentences. Put two spaces after the period if another sentence follows (for English text; might be inappropriate in other languages).
> >> ```
> >>
> >> I also noticed that some existing DETAIL and HINT messages do not fully follow this guideline. But I believe new code should adhere to the documented style as much as possible. In particular, DETAIL and HINT messages should begin with a capital letter and follow the complete-sentence convention.
> > Hi, v2 attached, WIP, the only known remaining issue to me is that
> > windows might fail to compile as it probably doesn't have concept of
> > uid_t... I'm wondering what to do there.
>
>
> I don't think it will arise, as Windows doesn't have the siginfo stuff,
> AFAIK.
>

Hi Andrew. Ok, so V3 is attached with just one change: uid_t/pid_t
changed to uint32 to make win32 happy.

Perhaps one question is whether this should be toggleable with GUC or not.

-J.

Attachments:

  [text/x-patch] v3-0001-Add-errdetail-with-PID-and-UID-about-source-of-te.patch (13.5K, ../../CAKZiRmz6RxKoANQEJcC+K4AtBREGt5-5JcXjEotd6AsE2c2=Bw@mail.gmail.com/2-v3-0001-Add-errdetail-with-PID-and-UID-about-source-of-te.patch)
  download | inline diff:
From 1959b4133f33a4e0cbb98ce257b7517f8f3c46dc Mon Sep 17 00:00:00 2001
From: Jakub Wartak <jakub.wartak@enterprisedb.com>
Date: Tue, 17 Feb 2026 12:41:01 +0100
Subject: [PATCH v3] Add errdetail() with PID and UID about source of
 termination signal.

On Linux and FreeBSD we can use SA_SIGINFO to fetch additional information
about sender of the signal, which can aid troubleshooting. Sample log:
  FATAL:  terminating connection due to administrator command
  DETAIL:  Signal sent by PID 508477, UID 1000.

Author: Jakub Wartak <jakub.wartak@enterprisedb.com>
Reviewed-by: Jim Jones <jim.jones@uni-muenster.de>
Discussion: https://www.postgresql.org/message-id/CAKZiRmyrOWovZSdixpLd3PGMQXuQL_zw2Ght5XhHCkQ1uDsxjw%40mail.gmail.com
---
 configure                         | 42 +++++++++++++++++++++++++++++++
 configure.ac                      | 18 +++++++++++++
 meson.build                       |  4 +++
 src/backend/replication/syncrep.c | 12 +++++++--
 src/backend/tcop/postgres.c       | 42 +++++++++++++++++++++++++------
 src/backend/utils/init/globals.c  |  2 ++
 src/bin/psql/t/001_basic.pl       |  7 +++---
 src/include/miscadmin.h           |  2 ++
 src/include/pg_config.h.in        |  3 +++
 src/port/pqsignal.c               | 35 +++++++++++++++++++++++---
 10 files changed, 151 insertions(+), 16 deletions(-)

diff --git a/configure b/configure
index a285a6ec3d7..704c88aee3d 100755
--- a/configure
+++ b/configure
@@ -15693,6 +15693,48 @@ if test "$ac_cv_sizeof_off_t" -lt 8; then
   fi
 fi
 
+# Check for SA_SIGINFO extended signal handler availability
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for SA_SIGINFO" >&5
+$as_echo_n "checking for SA_SIGINFO... " >&6; }
+if ${ac_cv_have_sa_siginfo+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+
+    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+
+            #include <signal.h>
+            #include <stddef.h>
+
+int
+main ()
+{
+
+            struct sigaction sa;
+            sa.sa_flags = SA_SIGINFO;
+
+  ;
+  return 0;
+}
+
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_have_sa_siginfo=yes
+else
+  ac_cv_have_sa_siginfo=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_have_sa_siginfo" >&5
+$as_echo "$ac_cv_have_sa_siginfo" >&6; }
+
+if test "x$ac_cv_have_sa_siginfo" = "xyes"; then
+
+$as_echo "#define HAVE_SA_SIGINFO 1" >>confdefs.h
+
+fi
 
 ##
 ## Functions, global variables
diff --git a/configure.ac b/configure.ac
index 476a76c7991..183bc992126 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1822,6 +1822,24 @@ if test "$ac_cv_sizeof_off_t" -lt 8; then
   fi
 fi
 
+# Check for SA_SIGINFO extended signal handler availability
+AC_CACHE_CHECK([for SA_SIGINFO], [ac_cv_have_sa_siginfo], [
+    AC_COMPILE_IFELSE([
+        AC_LANG_PROGRAM([[
+            #include <signal.h>
+            #include <stddef.h>
+        ]], [[
+            struct sigaction sa;
+            sa.sa_flags = SA_SIGINFO;
+        ]])
+    ],
+    [ac_cv_have_sa_siginfo=yes],
+    [ac_cv_have_sa_siginfo=no])
+])
+
+if test "x$ac_cv_have_sa_siginfo" = "xyes"; then
+    AC_DEFINE([HAVE_SA_SIGINFO], 1, [Define to 1 if you have SA_SIGINFO available.])
+fi
 
 ##
 ## Functions, global variables
diff --git a/meson.build b/meson.build
index 5122706477d..3aa675e7ebb 100644
--- a/meson.build
+++ b/meson.build
@@ -2879,6 +2879,10 @@ if cc.has_member('struct sockaddr', 'sa_len',
   cdata.set('HAVE_STRUCT_SOCKADDR_SA_LEN', 1)
 endif
 
+if cc.has_header_symbol('signal.h', 'SA_SIGINFO')
+  cdata.set('HAVE_SA_SIGINFO', 1)
+endif
+
 if cc.has_member('struct tm', 'tm_zone',
     args: test_c_args, include_directories: postgres_inc,
     prefix: '''
diff --git a/src/backend/replication/syncrep.c b/src/backend/replication/syncrep.c
index d1582a5d711..74cd41adfd4 100644
--- a/src/backend/replication/syncrep.c
+++ b/src/backend/replication/syncrep.c
@@ -302,7 +302,11 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 			ereport(WARNING,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
 					 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
+					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby."),
+						proc_die_sender_pid == 0 ? 0 :
+							errdetail("Signal sent by PID %lld, UID %lld.",
+								(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+						));
 			whereToSendOutput = DestNone;
 			SyncRepCancelWait();
 			break;
@@ -319,7 +323,11 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 			QueryCancelPending = false;
 			ereport(WARNING,
 					(errmsg("canceling wait for synchronous replication due to user request"),
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
+					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby."),
+						proc_die_sender_pid == 0 ? 0 :
+							errdetail("Signal sent by PID %lld, UID %lld.",
+								(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+						));
 			SyncRepCancelWait();
 			break;
 		}
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index d01a09dd0c4..6e3a0ec8655 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -3357,15 +3357,27 @@ ProcessInterrupts(void)
 		else if (AmAutoVacuumWorkerProcess())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating autovacuum process due to administrator command")));
+					 errmsg("terminating autovacuum process due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %lld, UID %lld.",
+							(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+					));
 		else if (IsLogicalWorker())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating logical replication worker due to administrator command")));
+					 errmsg("terminating logical replication worker due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %lld, UID %lld.",
+							(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+					));
 		else if (IsLogicalLauncher())
 		{
 			ereport(DEBUG1,
-					(errmsg_internal("logical replication launcher shutting down")));
+					(errmsg_internal("logical replication launcher shutting down"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %lld, UID %lld.",
+							(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+					));
 
 			/*
 			 * The logical replication launcher can be stopped at any time.
@@ -3376,23 +3388,39 @@ ProcessInterrupts(void)
 		else if (AmWalReceiverProcess())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating walreceiver process due to administrator command")));
+					 errmsg("terminating walreceiver process due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %lld, UID %lld.",
+							(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+					));
 		else if (AmBackgroundWorkerProcess())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
 					 errmsg("terminating background worker \"%s\" due to administrator command",
-							MyBgworkerEntry->bgw_type)));
+							MyBgworkerEntry->bgw_type),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %lld, UID %lld.",
+							(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+					));
 		else if (AmIoWorkerProcess())
 		{
 			ereport(DEBUG1,
-					(errmsg_internal("io worker shutting down due to administrator command")));
+					(errmsg_internal("io worker shutting down due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %lld, UID %lld.",
+							(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+					));
 
 			proc_exit(0);
 		}
 		else
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating connection due to administrator command")));
+					 errmsg("terminating connection due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %lld, UID %lld.",
+							(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+					));
 	}
 
 	if (CheckClientConnectionPending)
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 36ad708b360..927c98b45ee 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -32,6 +32,8 @@ ProtocolVersion FrontendProtocol;
 volatile sig_atomic_t InterruptPending = false;
 volatile sig_atomic_t QueryCancelPending = false;
 volatile sig_atomic_t ProcDiePending = false;
+volatile uint32 proc_die_sender_pid = 0;
+volatile uint32 proc_die_sender_uid = 0;
 volatile sig_atomic_t CheckClientConnectionPending = false;
 volatile sig_atomic_t ClientConnectionLost = false;
 volatile sig_atomic_t IdleInTransactionSessionTimeoutPending = false;
diff --git a/src/bin/psql/t/001_basic.pl b/src/bin/psql/t/001_basic.pl
index 6839f27cbe5..7bd585d40e3 100644
--- a/src/bin/psql/t/001_basic.pl
+++ b/src/bin/psql/t/001_basic.pl
@@ -142,12 +142,11 @@ my ($ret, $out, $err) = $node->psql('postgres',
 is($ret, 2, 'server crash: psql exit code');
 like($out, qr/before/, 'server crash: output before crash');
 unlike($out, qr/AFTER/, 'server crash: no output after crash');
-is( $err,
-	'psql:<stdin>:2: FATAL:  terminating connection due to administrator command
-psql:<stdin>:2: server closed the connection unexpectedly
+like( $err, qr/psql:<stdin>:2: FATAL:  terminating connection due to administrator command
+(?:DETAIL:  Signal sent by PID \d+, UID \d+.\n)?psql:<stdin>:2: server closed the connection unexpectedly
 	This probably means the server terminated abnormally
 	before or while processing the request.
-psql:<stdin>:2: error: connection to server was lost',
+psql:<stdin>:2: error: connection to server was lost/,
 	'server crash: error message');
 
 # test \errverbose
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index f16f35659b9..38bae8bb809 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -90,6 +90,8 @@
 extern PGDLLIMPORT volatile sig_atomic_t InterruptPending;
 extern PGDLLIMPORT volatile sig_atomic_t QueryCancelPending;
 extern PGDLLIMPORT volatile sig_atomic_t ProcDiePending;
+extern PGDLLIMPORT volatile uint32 proc_die_sender_pid;
+extern PGDLLIMPORT volatile uint32 proc_die_sender_uid;
 extern PGDLLIMPORT volatile sig_atomic_t IdleInTransactionSessionTimeoutPending;
 extern PGDLLIMPORT volatile sig_atomic_t TransactionTimeoutPending;
 extern PGDLLIMPORT volatile sig_atomic_t IdleSessionTimeoutPending;
diff --git a/src/include/pg_config.h.in b/src/include/pg_config.h.in
index a0bd84376e7..1fbb2ce380a 100644
--- a/src/include/pg_config.h.in
+++ b/src/include/pg_config.h.in
@@ -340,6 +340,9 @@
 /* Define to 1 if you have the `rl_variable_bind' function. */
 #undef HAVE_RL_VARIABLE_BIND
 
+/* Define to 1 if you have SA_SIGINFO available. */
+#undef HAVE_SA_SIGINFO
+
 /* Define to 1 if you have the <security/pam_appl.h> header file. */
 #undef HAVE_SECURITY_PAM_APPL_H
 
diff --git a/src/port/pqsignal.c b/src/port/pqsignal.c
index fbdf9341c2f..5e61739fdc3 100644
--- a/src/port/pqsignal.c
+++ b/src/port/pqsignal.c
@@ -82,10 +82,19 @@ static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
  *
  * This wrapper also handles restoring the value of errno.
  */
+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+static void
+wrapper_handler(int signo, siginfo_t *info, void *context)
+#else
 static void
 wrapper_handler(SIGNAL_ARGS)
+#endif
 {
 	int			save_errno = errno;
+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+	/* SIGNAL_ARGS defines postgres_signal_arg */
+	int			postgres_signal_arg = signo;
+#endif
 
 	Assert(postgres_signal_arg > 0);
 	Assert(postgres_signal_arg < PG_NSIG);
@@ -105,6 +114,14 @@ wrapper_handler(SIGNAL_ARGS)
 		raise(postgres_signal_arg);
 		return;
 	}
+
+#ifdef HAVE_SA_SIGINFO
+	if (signo == SIGTERM && info)
+	{
+		proc_die_sender_pid = info->si_pid;
+		proc_die_sender_uid = info->si_uid;
+	}
+#endif
 #endif
 
 	(*pqsignal_handlers[postgres_signal_arg]) (postgres_signal_arg);
@@ -125,6 +142,7 @@ pqsignal(int signo, pqsigfunc func)
 #if !(defined(WIN32) && defined(FRONTEND))
 	struct sigaction act;
 #endif
+	bool		use_wrapper = false;
 
 	Assert(signo > 0);
 	Assert(signo < PG_NSIG);
@@ -132,13 +150,24 @@ pqsignal(int signo, pqsigfunc func)
 	if (func != SIG_IGN && func != SIG_DFL)
 	{
 		pqsignal_handlers[signo] = func;	/* assumed atomic */
-		func = wrapper_handler;
+		use_wrapper = true;
 	}
 
 #if !(defined(WIN32) && defined(FRONTEND))
-	act.sa_handler = func;
 	sigemptyset(&act.sa_mask);
 	act.sa_flags = SA_RESTART;
+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+	if (use_wrapper)
+	{
+		act.sa_sigaction = wrapper_handler;
+		act.sa_flags |= SA_SIGINFO;
+	}
+	else
+		act.sa_handler = func;
+#else
+	act.sa_handler = use_wrapper ? wrapper_handler : func;
+#endif
+
 #ifdef SA_NOCLDSTOP
 	if (signo == SIGCHLD)
 		act.sa_flags |= SA_NOCLDSTOP;
@@ -147,7 +176,7 @@ pqsignal(int signo, pqsigfunc func)
 		Assert(false);			/* probably indicates coding error */
 #else
 	/* Forward to Windows native signal system. */
-	if (signal(signo, func) == SIG_ERR)
+	if (signal(signo, use_wrapper ? wrapper_handler : func) == SIG_ERR)
 		Assert(false);			/* probably indicates coding error */
 #endif
 }
-- 
2.43.0



^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-02-25 09:15  Chao Li <li.evan.chao@gmail.com>
  parent: Jakub Wartak <jakub.wartak@enterprisedb.com>
  0 siblings, 1 reply; 54+ messages in thread

From: Chao Li @ 2026-02-25 09:15 UTC (permalink / raw)
  To: Jakub Wartak <jakub.wartak@enterprisedb.com>; +Cc: Andrew Dunstan <andrew@dunslane.net>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>



> On Feb 25, 2026, at 16:26, Jakub Wartak <jakub.wartak@enterprisedb.com> wrote:
> 
> On Tue, Feb 24, 2026 at 5:15 PM Andrew Dunstan <andrew@dunslane.net> wrote:
>> 
>> 
>> On 2026-02-24 Tu 5:05 AM, Jakub Wartak wrote:
>>> On Tue, Feb 24, 2026 at 9:40 AM Chao Li <li.evan.chao@gmail.com> wrote:
>>> [..]
>>> 
>>>> There is guidance in the documentation regarding error message style: https://www.postgresql.org/docs/current/error-style-guide.html
>>>> ```
>>>> Detail and hint messages: Use complete sentences, and end each with a period. Capitalize the first word of sentences. Put two spaces after the period if another sentence follows (for English text; might be inappropriate in other languages).
>>>> ```
>>>> 
>>>> I also noticed that some existing DETAIL and HINT messages do not fully follow this guideline. But I believe new code should adhere to the documented style as much as possible. In particular, DETAIL and HINT messages should begin with a capital letter and follow the complete-sentence convention.
>>> Hi, v2 attached, WIP, the only known remaining issue to me is that
>>> windows might fail to compile as it probably doesn't have concept of
>>> uid_t... I'm wondering what to do there.
>> 
>> 
>> I don't think it will arise, as Windows doesn't have the siginfo stuff,
>> AFAIK.
>> 
> 
> Hi Andrew. Ok, so V3 is attached with just one change: uid_t/pid_t
> changed to uint32 to make win32 happy.
> 
> Perhaps one question is whether this should be toggleable with GUC or not.
> 
> -J.
> <v3-0001-Add-errdetail-with-PID-and-UID-about-source-of-te.patch>

A few comments for v3:

1 - syncrep.c
```
@@ -302,7 +302,11 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 			ereport(WARNING,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
 					 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
+					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby."),
+						proc_die_sender_pid == 0 ? 0 :
+							errdetail("Signal sent by PID %lld, UID %lld.",
+								(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+						));
```

Here errdetail is used twice. I guess the second conditional one should be errhint.

2 - syncrep.c
```
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
+					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby."),
+						proc_die_sender_pid == 0 ? 0 :
+							errdetail("Signal sent by PID %lld, UID %lld.",
+								(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+						));
```

Same as comment 1.

3
```
+volatile uint32 proc_die_sender_pid = 0;
+volatile uint32 proc_die_sender_uid = 0;
```

These two globals are only written in the signal handler, I think they should be sig_atomic_t to ensure atomic writes.

4
```
-					 errmsg("terminating walreceiver process due to administrator command")));
+					 errmsg("terminating walreceiver process due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %lld, UID %lld.",
+							(long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
+					));
```

Why do we need to format pid and uid in “long long” format? I searched over the source tree, the current postmaster.c just formats pid as int (%d):
```
	/* in parent, successful fork */
	ereport(DEBUG2,
			(errmsg_internal("forked new %s, pid=%d socket=%d",
							 GetBackendTypeDesc(bn->bkend_type),
							 (int) pid, (int) client_sock->sock)));
```

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/









^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-02-25 10:45  Jakub Wartak <jakub.wartak@enterprisedb.com>
  parent: Chao Li <li.evan.chao@gmail.com>
  0 siblings, 1 reply; 54+ messages in thread

From: Jakub Wartak @ 2026-02-25 10:45 UTC (permalink / raw)
  To: Chao Li <li.evan.chao@gmail.com>; +Cc: Andrew Dunstan <andrew@dunslane.net>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Wed, Feb 25, 2026 at 10:15 AM Chao Li <li.evan.chao@gmail.com> wrote:

Hi Chao, thanks for review.

> A few comments for v3:
>
> 1 - syncrep.c
[..]
> +                                               proc_die_sender_pid == 0 ? 0 :
> +                                                       errdetail("Signal sent by PID %lld, UID %lld.",
> +                                                               (long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
> +                                               ));
> ```
>
> Here errdetail is used twice. I guess the second conditional one should be errhint.
>
> 2 - syncrep.c
[..]
> Same as comment 1.

You are right, apparently I copy/pasted code from src/backend/tcop/postgres.c
way too fast... fixed.

> 3
> ```
> +volatile uint32 proc_die_sender_pid = 0;
> +volatile uint32 proc_die_sender_uid = 0;
> ```
>
> These two globals are only written in the signal handler, I think they should be sig_atomic_t to ensure atomic writes.

Well the problem that sig_atomic_t is int and we need at least uint32 and
I couldn't find better way. I think that 4 bytes writes will be mostly
always atomic (for 64-bits it would depend on
PG_HAVE_8BYTE_SINGLE_COPY_ATOMICITY)

Yet I moved those little below, so it's more aligned to the other uses.

> 4
> ```
> -                                        errmsg("terminating walreceiver process due to administrator command")));
> +                                        errmsg("terminating walreceiver process due to administrator command"),
> +                                        proc_die_sender_pid == 0 ? 0 :
> +                                               errdetail("Signal sent by PID %lld, UID %lld.",
> +                                                       (long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
> +                                       ));
> ```
>
> Why do we need to format pid and uid in “long long” format? I searched over the source tree, the current postmaster.c just formats pid as int (%d):
> ```
>         /* in parent, successful fork */
>         ereport(DEBUG2,
>                         (errmsg_internal("forked new %s, pid=%d socket=%d",
>                                                          GetBackendTypeDesc(bn->bkend_type),
>                                                          (int) pid, (int) client_sock->sock)));
> ```

Yes, I think I was kind of lost when thinking about it (v1 had sig_atomic_t,
later had pid_t, I read somewhere about 64-bit pids, and so on) vs
platform-agnostic hell of putting that into printf). Possible I was
overthinking it
and I have reverted it to just using %d with that uint32. BTW I've also found:
   elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);

v4 attached. Thanks again for the review.

-J.

Attachments:

  [text/x-patch] v4-0001-Add-errdetail-with-PID-and-UID-about-source-of-te.patch (13.2K, ../../CAKZiRmzmV6H4Cg=Yn=-i0myrTp2qhK_vuNAtFJppiQXmPmgy3A@mail.gmail.com/2-v4-0001-Add-errdetail-with-PID-and-UID-about-source-of-te.patch)
  download | inline diff:
From 5b9b093bad3ab159cb93e838ff640b37f72588b2 Mon Sep 17 00:00:00 2001
From: Jakub Wartak <jakub.wartak@enterprisedb.com>
Date: Tue, 17 Feb 2026 12:41:01 +0100
Subject: [PATCH v4] Add errdetail() with PID and UID about source of
 termination signal.

On Linux and FreeBSD we can use SA_SIGINFO to fetch additional information
about sender of the signal, which can aid troubleshooting. Sample log:
  FATAL:  terminating connection due to administrator command
  DETAIL:  Signal sent by PID 508477, UID 1000.

Author: Jakub Wartak <jakub.wartak@enterprisedb.com>
Reviewed-by: Jim Jones <jim.jones@uni-muenster.de>
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://www.postgresql.org/message-id/CAKZiRmyrOWovZSdixpLd3PGMQXuQL_zw2Ght5XhHCkQ1uDsxjw%40mail.gmail.com
---
 configure                         | 42 +++++++++++++++++++++++++++++++
 configure.ac                      | 18 +++++++++++++
 meson.build                       |  4 +++
 src/backend/replication/syncrep.c | 12 +++++++--
 src/backend/tcop/postgres.c       | 42 +++++++++++++++++++++++++------
 src/backend/utils/init/globals.c  |  2 ++
 src/bin/psql/t/001_basic.pl       |  7 +++---
 src/include/miscadmin.h           |  2 ++
 src/include/pg_config.h.in        |  3 +++
 src/port/pqsignal.c               | 35 +++++++++++++++++++++++---
 10 files changed, 151 insertions(+), 16 deletions(-)

diff --git a/configure b/configure
index a285a6ec3d7..704c88aee3d 100755
--- a/configure
+++ b/configure
@@ -15693,6 +15693,48 @@ if test "$ac_cv_sizeof_off_t" -lt 8; then
   fi
 fi
 
+# Check for SA_SIGINFO extended signal handler availability
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for SA_SIGINFO" >&5
+$as_echo_n "checking for SA_SIGINFO... " >&6; }
+if ${ac_cv_have_sa_siginfo+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+
+    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+
+            #include <signal.h>
+            #include <stddef.h>
+
+int
+main ()
+{
+
+            struct sigaction sa;
+            sa.sa_flags = SA_SIGINFO;
+
+  ;
+  return 0;
+}
+
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_have_sa_siginfo=yes
+else
+  ac_cv_have_sa_siginfo=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_have_sa_siginfo" >&5
+$as_echo "$ac_cv_have_sa_siginfo" >&6; }
+
+if test "x$ac_cv_have_sa_siginfo" = "xyes"; then
+
+$as_echo "#define HAVE_SA_SIGINFO 1" >>confdefs.h
+
+fi
 
 ##
 ## Functions, global variables
diff --git a/configure.ac b/configure.ac
index 476a76c7991..183bc992126 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1822,6 +1822,24 @@ if test "$ac_cv_sizeof_off_t" -lt 8; then
   fi
 fi
 
+# Check for SA_SIGINFO extended signal handler availability
+AC_CACHE_CHECK([for SA_SIGINFO], [ac_cv_have_sa_siginfo], [
+    AC_COMPILE_IFELSE([
+        AC_LANG_PROGRAM([[
+            #include <signal.h>
+            #include <stddef.h>
+        ]], [[
+            struct sigaction sa;
+            sa.sa_flags = SA_SIGINFO;
+        ]])
+    ],
+    [ac_cv_have_sa_siginfo=yes],
+    [ac_cv_have_sa_siginfo=no])
+])
+
+if test "x$ac_cv_have_sa_siginfo" = "xyes"; then
+    AC_DEFINE([HAVE_SA_SIGINFO], 1, [Define to 1 if you have SA_SIGINFO available.])
+fi
 
 ##
 ## Functions, global variables
diff --git a/meson.build b/meson.build
index 5122706477d..3aa675e7ebb 100644
--- a/meson.build
+++ b/meson.build
@@ -2879,6 +2879,10 @@ if cc.has_member('struct sockaddr', 'sa_len',
   cdata.set('HAVE_STRUCT_SOCKADDR_SA_LEN', 1)
 endif
 
+if cc.has_header_symbol('signal.h', 'SA_SIGINFO')
+  cdata.set('HAVE_SA_SIGINFO', 1)
+endif
+
 if cc.has_member('struct tm', 'tm_zone',
     args: test_c_args, include_directories: postgres_inc,
     prefix: '''
diff --git a/src/backend/replication/syncrep.c b/src/backend/replication/syncrep.c
index d1582a5d711..9b0e899ac1a 100644
--- a/src/backend/replication/syncrep.c
+++ b/src/backend/replication/syncrep.c
@@ -302,7 +302,11 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 			ereport(WARNING,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
 					 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
+					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby."),
+						proc_die_sender_pid == 0 ? 0 :
+							errhint("Signal sent by PID %d, UID %d.",
+								proc_die_sender_pid, proc_die_sender_uid)
+						));
 			whereToSendOutput = DestNone;
 			SyncRepCancelWait();
 			break;
@@ -319,7 +323,11 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 			QueryCancelPending = false;
 			ereport(WARNING,
 					(errmsg("canceling wait for synchronous replication due to user request"),
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
+					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby."),
+						proc_die_sender_pid == 0 ? 0 :
+							errhint("Signal sent by PID %d, UID %d.",
+								proc_die_sender_pid, proc_die_sender_uid)
+						));
 			SyncRepCancelWait();
 			break;
 		}
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index d01a09dd0c4..5735d93605c 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -3357,15 +3357,27 @@ ProcessInterrupts(void)
 		else if (AmAutoVacuumWorkerProcess())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating autovacuum process due to administrator command")));
+					 errmsg("terminating autovacuum process due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 		else if (IsLogicalWorker())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating logical replication worker due to administrator command")));
+					 errmsg("terminating logical replication worker due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 		else if (IsLogicalLauncher())
 		{
 			ereport(DEBUG1,
-					(errmsg_internal("logical replication launcher shutting down")));
+					(errmsg_internal("logical replication launcher shutting down"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 
 			/*
 			 * The logical replication launcher can be stopped at any time.
@@ -3376,23 +3388,39 @@ ProcessInterrupts(void)
 		else if (AmWalReceiverProcess())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating walreceiver process due to administrator command")));
+					 errmsg("terminating walreceiver process due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 		else if (AmBackgroundWorkerProcess())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
 					 errmsg("terminating background worker \"%s\" due to administrator command",
-							MyBgworkerEntry->bgw_type)));
+							MyBgworkerEntry->bgw_type),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 		else if (AmIoWorkerProcess())
 		{
 			ereport(DEBUG1,
-					(errmsg_internal("io worker shutting down due to administrator command")));
+					(errmsg_internal("io worker shutting down due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 
 			proc_exit(0);
 		}
 		else
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating connection due to administrator command")));
+					 errmsg("terminating connection due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errdetail("Signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 	}
 
 	if (CheckClientConnectionPending)
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 36ad708b360..80ad00fbe0a 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -43,6 +43,8 @@ volatile sig_atomic_t IdleStatsUpdateTimeoutPending = false;
 volatile uint32 InterruptHoldoffCount = 0;
 volatile uint32 QueryCancelHoldoffCount = 0;
 volatile uint32 CritSectionCount = 0;
+volatile uint32 proc_die_sender_pid = 0;
+volatile uint32 proc_die_sender_uid = 0;
 
 int			MyProcPid;
 pg_time_t	MyStartTime;
diff --git a/src/bin/psql/t/001_basic.pl b/src/bin/psql/t/001_basic.pl
index 6839f27cbe5..7bd585d40e3 100644
--- a/src/bin/psql/t/001_basic.pl
+++ b/src/bin/psql/t/001_basic.pl
@@ -142,12 +142,11 @@ my ($ret, $out, $err) = $node->psql('postgres',
 is($ret, 2, 'server crash: psql exit code');
 like($out, qr/before/, 'server crash: output before crash');
 unlike($out, qr/AFTER/, 'server crash: no output after crash');
-is( $err,
-	'psql:<stdin>:2: FATAL:  terminating connection due to administrator command
-psql:<stdin>:2: server closed the connection unexpectedly
+like( $err, qr/psql:<stdin>:2: FATAL:  terminating connection due to administrator command
+(?:DETAIL:  Signal sent by PID \d+, UID \d+.\n)?psql:<stdin>:2: server closed the connection unexpectedly
 	This probably means the server terminated abnormally
 	before or while processing the request.
-psql:<stdin>:2: error: connection to server was lost',
+psql:<stdin>:2: error: connection to server was lost/,
 	'server crash: error message');
 
 # test \errverbose
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index f16f35659b9..38bae8bb809 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -90,6 +90,8 @@
 extern PGDLLIMPORT volatile sig_atomic_t InterruptPending;
 extern PGDLLIMPORT volatile sig_atomic_t QueryCancelPending;
 extern PGDLLIMPORT volatile sig_atomic_t ProcDiePending;
+extern PGDLLIMPORT volatile uint32 proc_die_sender_pid;
+extern PGDLLIMPORT volatile uint32 proc_die_sender_uid;
 extern PGDLLIMPORT volatile sig_atomic_t IdleInTransactionSessionTimeoutPending;
 extern PGDLLIMPORT volatile sig_atomic_t TransactionTimeoutPending;
 extern PGDLLIMPORT volatile sig_atomic_t IdleSessionTimeoutPending;
diff --git a/src/include/pg_config.h.in b/src/include/pg_config.h.in
index a0bd84376e7..1fbb2ce380a 100644
--- a/src/include/pg_config.h.in
+++ b/src/include/pg_config.h.in
@@ -340,6 +340,9 @@
 /* Define to 1 if you have the `rl_variable_bind' function. */
 #undef HAVE_RL_VARIABLE_BIND
 
+/* Define to 1 if you have SA_SIGINFO available. */
+#undef HAVE_SA_SIGINFO
+
 /* Define to 1 if you have the <security/pam_appl.h> header file. */
 #undef HAVE_SECURITY_PAM_APPL_H
 
diff --git a/src/port/pqsignal.c b/src/port/pqsignal.c
index fbdf9341c2f..5e61739fdc3 100644
--- a/src/port/pqsignal.c
+++ b/src/port/pqsignal.c
@@ -82,10 +82,19 @@ static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
  *
  * This wrapper also handles restoring the value of errno.
  */
+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+static void
+wrapper_handler(int signo, siginfo_t *info, void *context)
+#else
 static void
 wrapper_handler(SIGNAL_ARGS)
+#endif
 {
 	int			save_errno = errno;
+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+	/* SIGNAL_ARGS defines postgres_signal_arg */
+	int			postgres_signal_arg = signo;
+#endif
 
 	Assert(postgres_signal_arg > 0);
 	Assert(postgres_signal_arg < PG_NSIG);
@@ -105,6 +114,14 @@ wrapper_handler(SIGNAL_ARGS)
 		raise(postgres_signal_arg);
 		return;
 	}
+
+#ifdef HAVE_SA_SIGINFO
+	if (signo == SIGTERM && info)
+	{
+		proc_die_sender_pid = info->si_pid;
+		proc_die_sender_uid = info->si_uid;
+	}
+#endif
 #endif
 
 	(*pqsignal_handlers[postgres_signal_arg]) (postgres_signal_arg);
@@ -125,6 +142,7 @@ pqsignal(int signo, pqsigfunc func)
 #if !(defined(WIN32) && defined(FRONTEND))
 	struct sigaction act;
 #endif
+	bool		use_wrapper = false;
 
 	Assert(signo > 0);
 	Assert(signo < PG_NSIG);
@@ -132,13 +150,24 @@ pqsignal(int signo, pqsigfunc func)
 	if (func != SIG_IGN && func != SIG_DFL)
 	{
 		pqsignal_handlers[signo] = func;	/* assumed atomic */
-		func = wrapper_handler;
+		use_wrapper = true;
 	}
 
 #if !(defined(WIN32) && defined(FRONTEND))
-	act.sa_handler = func;
 	sigemptyset(&act.sa_mask);
 	act.sa_flags = SA_RESTART;
+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+	if (use_wrapper)
+	{
+		act.sa_sigaction = wrapper_handler;
+		act.sa_flags |= SA_SIGINFO;
+	}
+	else
+		act.sa_handler = func;
+#else
+	act.sa_handler = use_wrapper ? wrapper_handler : func;
+#endif
+
 #ifdef SA_NOCLDSTOP
 	if (signo == SIGCHLD)
 		act.sa_flags |= SA_NOCLDSTOP;
@@ -147,7 +176,7 @@ pqsignal(int signo, pqsigfunc func)
 		Assert(false);			/* probably indicates coding error */
 #else
 	/* Forward to Windows native signal system. */
-	if (signal(signo, func) == SIG_ERR)
+	if (signal(signo, use_wrapper ? wrapper_handler : func) == SIG_ERR)
 		Assert(false);			/* probably indicates coding error */
 #endif
 }
-- 
2.43.0



^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-02-26 03:08  Chao Li <li.evan.chao@gmail.com>
  parent: Jakub Wartak <jakub.wartak@enterprisedb.com>
  0 siblings, 1 reply; 54+ messages in thread

From: Chao Li @ 2026-02-26 03:08 UTC (permalink / raw)
  To: Jakub Wartak <jakub.wartak@enterprisedb.com>; +Cc: Andrew Dunstan <andrew@dunslane.net>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>



> On Feb 25, 2026, at 18:45, Jakub Wartak <jakub.wartak@enterprisedb.com> wrote:
> 
> On Wed, Feb 25, 2026 at 10:15 AM Chao Li <li.evan.chao@gmail.com> wrote:
> 
> Hi Chao, thanks for review.
> 
>> A few comments for v3:
>> 
>> 1 - syncrep.c
> [..]
>> +                                               proc_die_sender_pid == 0 ? 0 :
>> +                                                       errdetail("Signal sent by PID %lld, UID %lld.",
>> +                                                               (long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
>> +                                               ));
>> ```
>> 
>> Here errdetail is used twice. I guess the second conditional one should be errhint.
>> 
>> 2 - syncrep.c
> [..]
>> Same as comment 1.
> 
> You are right, apparently I copy/pasted code from src/backend/tcop/postgres.c
> way too fast... fixed.
> 
>> 3
>> ```
>> +volatile uint32 proc_die_sender_pid = 0;
>> +volatile uint32 proc_die_sender_uid = 0;
>> ```
>> 
>> These two globals are only written in the signal handler, I think they should be sig_atomic_t to ensure atomic writes.
> 
> Well the problem that sig_atomic_t is int and we need at least uint32 and
> I couldn't find better way. I think that 4 bytes writes will be mostly
> always atomic (for 64-bits it would depend on
> PG_HAVE_8BYTE_SINGLE_COPY_ATOMICITY)
> 
> Yet I moved those little below, so it's more aligned to the other uses.
> 
>> 4
>> ```
>> -                                        errmsg("terminating walreceiver process due to administrator command")));
>> +                                        errmsg("terminating walreceiver process due to administrator command"),
>> +                                        proc_die_sender_pid == 0 ? 0 :
>> +                                               errdetail("Signal sent by PID %lld, UID %lld.",
>> +                                                       (long long)proc_die_sender_pid, (long long)proc_die_sender_uid)
>> +                                       ));
>> ```
>> 
>> Why do we need to format pid and uid in “long long” format? I searched over the source tree, the current postmaster.c just formats pid as int (%d):
>> ```
>>        /* in parent, successful fork */
>>        ereport(DEBUG2,
>>                        (errmsg_internal("forked new %s, pid=%d socket=%d",
>>                                                         GetBackendTypeDesc(bn->bkend_type),
>>                                                         (int) pid, (int) client_sock->sock)));
>> ```
> 
> Yes, I think I was kind of lost when thinking about it (v1 had sig_atomic_t,
> later had pid_t, I read somewhere about 64-bit pids, and so on) vs
> platform-agnostic hell of putting that into printf). Possible I was
> overthinking it
> and I have reverted it to just using %d with that uint32. BTW I've also found:
>   elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
> 
> v4 attached. Thanks again for the review.
> 
> -J.
> <v4-0001-Add-errdetail-with-PID-and-UID-about-source-of-te.patch>

I just reviewed v4 again and got a few more comments:

1. This patch only set the global proc_die_sender_pid/uid to 0 at startup, then assign values to them upon receiving SIGTERM, and never reset them, which assumes a process must die upon SIGTERM. Is the assumption true? I guess not. If a process receives SIGTERM and not die immediately, then die for other reason, then it may report a misleading PID and UID. So, I think we may need to reset proc_die_sender_pid/uid somewhere. For example, in ProcessInterrupts(), copy them to local variables and reset them to 0, then use the local variables for ereport().

2. 
```
@@ -319,7 +323,11 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 			ereport(WARNING,
 					(errmsg("canceling wait for synchronous replication due to user request"),
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
+					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby."),
+						proc_die_sender_pid == 0 ? 0 :
+							errhint("Signal sent by PID %d, UID %d.",
+								proc_die_sender_pid, proc_die_sender_uid)
+						));
```

syncrpe.c uses errhint to print PID and UID, and postgres.c uses errdetail. We should keep consistency, maybe all use errhint.

3.
```
@@ -319,7 +323,11 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 			QueryCancelPending = false;
 			ereport(WARNING,
 					(errmsg("canceling wait for synchronous replication due to user request"),
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
+					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby."),
+						proc_die_sender_pid == 0 ? 0 :
+							errhint("Signal sent by PID %d, UID %d.",
+								proc_die_sender_pid, proc_die_sender_uid)
+						));
 			SyncRepCancelWait();
 			break;
 		}
```

I don’t think the query cancel case relates to SIGTERM, so we don’t need to log PID and UID here.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/









^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-02-26 09:25  Jakub Wartak <jakub.wartak@enterprisedb.com>
  parent: Chao Li <li.evan.chao@gmail.com>
  0 siblings, 1 reply; 54+ messages in thread

From: Jakub Wartak @ 2026-02-26 09:25 UTC (permalink / raw)
  To: Chao Li <li.evan.chao@gmail.com>; +Cc: Andrew Dunstan <andrew@dunslane.net>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Thu, Feb 26, 2026 at 4:09 AM Chao Li <li.evan.chao@gmail.com> wrote:

Hi Chao,

> I just reviewed v4 again and got a few more comments:
>
> 1. This patch only set the global proc_die_sender_pid/uid to 0 at startup, then assign values to them upon receiving SIGTERM, and never reset them, which assumes a process must die upon SIGTERM. Is the assumption true? I guess not. If a process receives SIGTERM and not die immediately, then die for other reason, then it may report a misleading PID and UID.

Hmm, I'm not sure I follow. If we receive SIGTERM and not die immediately
(for whatever reason), then two scenarios can happen as far as I'm concerned:
* another SIGTERM comes in from the same or different uid/pid and it wll be
reported properly
* different SIGKILL, but in this case we won't report UID/PID at all

am I missing something or do You have any particular scenario in mind?
The flow will be wrapper_handler()->die()->SetLatch()->..->directyl to
err reporting facilities.

> 2.
> syncrpe.c uses errhint to print PID and UID, and postgres.c uses errdetail. We should keep consistency, maybe all use errhint.

Right, let's make it that way.

> 3.
> ```
> @@ -319,7 +323,11 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
>                         QueryCancelPending = false;
>                         ereport(WARNING,
>                                         (errmsg("canceling wait for synchronous replication due to user request"),
> -                                        errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
> +                                        errdetail("The transaction has already committed locally, but might not have been replicated to the standby."),
> +                                               proc_die_sender_pid == 0 ? 0 :
> +                                                       errhint("Signal sent by PID %d, UID %d.",
> +                                                               proc_die_sender_pid, proc_die_sender_uid)
> +                                               ));
>                         SyncRepCancelWait();
>                         break;
>                 }
> ```
>
> I don’t think the query cancel case relates to SIGTERM, so we don’t need to log PID and UID here.

Right, it was superfluous.

v5 attached.

-J.

Attachments:

  [text/x-patch] v5-0001-Add-errdetail-with-PID-and-UID-about-source-of-te.patch (12.5K, ../../CAKZiRmxvdYXhO1JrVLW3LkuoaTjYpKmhOzzOCOhw4wDM3rYRMQ@mail.gmail.com/2-v5-0001-Add-errdetail-with-PID-and-UID-about-source-of-te.patch)
  download | inline diff:
From fa2b26d736a8bd6a830789be3dafed1201be9a5f Mon Sep 17 00:00:00 2001
From: Jakub Wartak <jakub.wartak@enterprisedb.com>
Date: Tue, 17 Feb 2026 12:41:01 +0100
Subject: [PATCH v5] Add errdetail() with PID and UID about source of
 termination signal.

On Linux and FreeBSD we can use SA_SIGINFO to fetch additional information
about sender of the signal, which can aid troubleshooting. Sample log:
  FATAL:  terminating connection due to administrator command
  DETAIL:  Signal sent by PID 508477, UID 1000.

Author: Jakub Wartak <jakub.wartak@enterprisedb.com>
Reviewed-by: Jim Jones <jim.jones@uni-muenster.de>
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://www.postgresql.org/message-id/CAKZiRmyrOWovZSdixpLd3PGMQXuQL_zw2Ght5XhHCkQ1uDsxjw%40mail.gmail.com
---
 configure                         | 42 +++++++++++++++++++++++++++++++
 configure.ac                      | 18 +++++++++++++
 meson.build                       |  4 +++
 src/backend/replication/syncrep.c |  6 ++++-
 src/backend/tcop/postgres.c       | 42 +++++++++++++++++++++++++------
 src/backend/utils/init/globals.c  |  2 ++
 src/bin/psql/t/001_basic.pl       |  7 +++---
 src/include/miscadmin.h           |  2 ++
 src/include/pg_config.h.in        |  3 +++
 src/port/pqsignal.c               | 35 +++++++++++++++++++++++---
 10 files changed, 146 insertions(+), 15 deletions(-)

diff --git a/configure b/configure
index a285a6ec3d7..704c88aee3d 100755
--- a/configure
+++ b/configure
@@ -15693,6 +15693,48 @@ if test "$ac_cv_sizeof_off_t" -lt 8; then
   fi
 fi
 
+# Check for SA_SIGINFO extended signal handler availability
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for SA_SIGINFO" >&5
+$as_echo_n "checking for SA_SIGINFO... " >&6; }
+if ${ac_cv_have_sa_siginfo+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+
+    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+
+            #include <signal.h>
+            #include <stddef.h>
+
+int
+main ()
+{
+
+            struct sigaction sa;
+            sa.sa_flags = SA_SIGINFO;
+
+  ;
+  return 0;
+}
+
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_have_sa_siginfo=yes
+else
+  ac_cv_have_sa_siginfo=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_have_sa_siginfo" >&5
+$as_echo "$ac_cv_have_sa_siginfo" >&6; }
+
+if test "x$ac_cv_have_sa_siginfo" = "xyes"; then
+
+$as_echo "#define HAVE_SA_SIGINFO 1" >>confdefs.h
+
+fi
 
 ##
 ## Functions, global variables
diff --git a/configure.ac b/configure.ac
index 476a76c7991..183bc992126 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1822,6 +1822,24 @@ if test "$ac_cv_sizeof_off_t" -lt 8; then
   fi
 fi
 
+# Check for SA_SIGINFO extended signal handler availability
+AC_CACHE_CHECK([for SA_SIGINFO], [ac_cv_have_sa_siginfo], [
+    AC_COMPILE_IFELSE([
+        AC_LANG_PROGRAM([[
+            #include <signal.h>
+            #include <stddef.h>
+        ]], [[
+            struct sigaction sa;
+            sa.sa_flags = SA_SIGINFO;
+        ]])
+    ],
+    [ac_cv_have_sa_siginfo=yes],
+    [ac_cv_have_sa_siginfo=no])
+])
+
+if test "x$ac_cv_have_sa_siginfo" = "xyes"; then
+    AC_DEFINE([HAVE_SA_SIGINFO], 1, [Define to 1 if you have SA_SIGINFO available.])
+fi
 
 ##
 ## Functions, global variables
diff --git a/meson.build b/meson.build
index 5122706477d..3aa675e7ebb 100644
--- a/meson.build
+++ b/meson.build
@@ -2879,6 +2879,10 @@ if cc.has_member('struct sockaddr', 'sa_len',
   cdata.set('HAVE_STRUCT_SOCKADDR_SA_LEN', 1)
 endif
 
+if cc.has_header_symbol('signal.h', 'SA_SIGINFO')
+  cdata.set('HAVE_SA_SIGINFO', 1)
+endif
+
 if cc.has_member('struct tm', 'tm_zone',
     args: test_c_args, include_directories: postgres_inc,
     prefix: '''
diff --git a/src/backend/replication/syncrep.c b/src/backend/replication/syncrep.c
index d1582a5d711..fd5fb1e01f9 100644
--- a/src/backend/replication/syncrep.c
+++ b/src/backend/replication/syncrep.c
@@ -302,7 +302,11 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 			ereport(WARNING,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
 					 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
+					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby."),
+						proc_die_sender_pid == 0 ? 0 :
+							errhint("Signal sent by PID %d, UID %d.",
+								proc_die_sender_pid, proc_die_sender_uid)
+						));
 			whereToSendOutput = DestNone;
 			SyncRepCancelWait();
 			break;
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index d01a09dd0c4..e1fad1e895b 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -3357,15 +3357,27 @@ ProcessInterrupts(void)
 		else if (AmAutoVacuumWorkerProcess())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating autovacuum process due to administrator command")));
+					 errmsg("terminating autovacuum process due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errhint("Signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 		else if (IsLogicalWorker())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating logical replication worker due to administrator command")));
+					 errmsg("terminating logical replication worker due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errhint("Signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 		else if (IsLogicalLauncher())
 		{
 			ereport(DEBUG1,
-					(errmsg_internal("logical replication launcher shutting down")));
+					(errmsg_internal("logical replication launcher shutting down"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errhint("Signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 
 			/*
 			 * The logical replication launcher can be stopped at any time.
@@ -3376,23 +3388,39 @@ ProcessInterrupts(void)
 		else if (AmWalReceiverProcess())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating walreceiver process due to administrator command")));
+					 errmsg("terminating walreceiver process due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errhint("Signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 		else if (AmBackgroundWorkerProcess())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
 					 errmsg("terminating background worker \"%s\" due to administrator command",
-							MyBgworkerEntry->bgw_type)));
+							MyBgworkerEntry->bgw_type),
+					 proc_die_sender_pid == 0 ? 0 :
+						errhint("Signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 		else if (AmIoWorkerProcess())
 		{
 			ereport(DEBUG1,
-					(errmsg_internal("io worker shutting down due to administrator command")));
+					(errmsg_internal("io worker shutting down due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errhint("Signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 
 			proc_exit(0);
 		}
 		else
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating connection due to administrator command")));
+					 errmsg("terminating connection due to administrator command"),
+					 proc_die_sender_pid == 0 ? 0 :
+						errhint("Signal sent by PID %d, UID %d.",
+							proc_die_sender_pid, proc_die_sender_uid)
+					));
 	}
 
 	if (CheckClientConnectionPending)
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 36ad708b360..80ad00fbe0a 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -43,6 +43,8 @@ volatile sig_atomic_t IdleStatsUpdateTimeoutPending = false;
 volatile uint32 InterruptHoldoffCount = 0;
 volatile uint32 QueryCancelHoldoffCount = 0;
 volatile uint32 CritSectionCount = 0;
+volatile uint32 proc_die_sender_pid = 0;
+volatile uint32 proc_die_sender_uid = 0;
 
 int			MyProcPid;
 pg_time_t	MyStartTime;
diff --git a/src/bin/psql/t/001_basic.pl b/src/bin/psql/t/001_basic.pl
index 6839f27cbe5..9f45c33b5f9 100644
--- a/src/bin/psql/t/001_basic.pl
+++ b/src/bin/psql/t/001_basic.pl
@@ -142,12 +142,11 @@ my ($ret, $out, $err) = $node->psql('postgres',
 is($ret, 2, 'server crash: psql exit code');
 like($out, qr/before/, 'server crash: output before crash');
 unlike($out, qr/AFTER/, 'server crash: no output after crash');
-is( $err,
-	'psql:<stdin>:2: FATAL:  terminating connection due to administrator command
-psql:<stdin>:2: server closed the connection unexpectedly
+like( $err, qr/psql:<stdin>:2: FATAL:  terminating connection due to administrator command
+(?:HINT:  Signal sent by PID \d+, UID \d+.\n)?psql:<stdin>:2: server closed the connection unexpectedly
 	This probably means the server terminated abnormally
 	before or while processing the request.
-psql:<stdin>:2: error: connection to server was lost',
+psql:<stdin>:2: error: connection to server was lost/,
 	'server crash: error message');
 
 # test \errverbose
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index f16f35659b9..38bae8bb809 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -90,6 +90,8 @@
 extern PGDLLIMPORT volatile sig_atomic_t InterruptPending;
 extern PGDLLIMPORT volatile sig_atomic_t QueryCancelPending;
 extern PGDLLIMPORT volatile sig_atomic_t ProcDiePending;
+extern PGDLLIMPORT volatile uint32 proc_die_sender_pid;
+extern PGDLLIMPORT volatile uint32 proc_die_sender_uid;
 extern PGDLLIMPORT volatile sig_atomic_t IdleInTransactionSessionTimeoutPending;
 extern PGDLLIMPORT volatile sig_atomic_t TransactionTimeoutPending;
 extern PGDLLIMPORT volatile sig_atomic_t IdleSessionTimeoutPending;
diff --git a/src/include/pg_config.h.in b/src/include/pg_config.h.in
index a0bd84376e7..1fbb2ce380a 100644
--- a/src/include/pg_config.h.in
+++ b/src/include/pg_config.h.in
@@ -340,6 +340,9 @@
 /* Define to 1 if you have the `rl_variable_bind' function. */
 #undef HAVE_RL_VARIABLE_BIND
 
+/* Define to 1 if you have SA_SIGINFO available. */
+#undef HAVE_SA_SIGINFO
+
 /* Define to 1 if you have the <security/pam_appl.h> header file. */
 #undef HAVE_SECURITY_PAM_APPL_H
 
diff --git a/src/port/pqsignal.c b/src/port/pqsignal.c
index fbdf9341c2f..5e61739fdc3 100644
--- a/src/port/pqsignal.c
+++ b/src/port/pqsignal.c
@@ -82,10 +82,19 @@ static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
  *
  * This wrapper also handles restoring the value of errno.
  */
+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+static void
+wrapper_handler(int signo, siginfo_t *info, void *context)
+#else
 static void
 wrapper_handler(SIGNAL_ARGS)
+#endif
 {
 	int			save_errno = errno;
+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+	/* SIGNAL_ARGS defines postgres_signal_arg */
+	int			postgres_signal_arg = signo;
+#endif
 
 	Assert(postgres_signal_arg > 0);
 	Assert(postgres_signal_arg < PG_NSIG);
@@ -105,6 +114,14 @@ wrapper_handler(SIGNAL_ARGS)
 		raise(postgres_signal_arg);
 		return;
 	}
+
+#ifdef HAVE_SA_SIGINFO
+	if (signo == SIGTERM && info)
+	{
+		proc_die_sender_pid = info->si_pid;
+		proc_die_sender_uid = info->si_uid;
+	}
+#endif
 #endif
 
 	(*pqsignal_handlers[postgres_signal_arg]) (postgres_signal_arg);
@@ -125,6 +142,7 @@ pqsignal(int signo, pqsigfunc func)
 #if !(defined(WIN32) && defined(FRONTEND))
 	struct sigaction act;
 #endif
+	bool		use_wrapper = false;
 
 	Assert(signo > 0);
 	Assert(signo < PG_NSIG);
@@ -132,13 +150,24 @@ pqsignal(int signo, pqsigfunc func)
 	if (func != SIG_IGN && func != SIG_DFL)
 	{
 		pqsignal_handlers[signo] = func;	/* assumed atomic */
-		func = wrapper_handler;
+		use_wrapper = true;
 	}
 
 #if !(defined(WIN32) && defined(FRONTEND))
-	act.sa_handler = func;
 	sigemptyset(&act.sa_mask);
 	act.sa_flags = SA_RESTART;
+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+	if (use_wrapper)
+	{
+		act.sa_sigaction = wrapper_handler;
+		act.sa_flags |= SA_SIGINFO;
+	}
+	else
+		act.sa_handler = func;
+#else
+	act.sa_handler = use_wrapper ? wrapper_handler : func;
+#endif
+
 #ifdef SA_NOCLDSTOP
 	if (signo == SIGCHLD)
 		act.sa_flags |= SA_NOCLDSTOP;
@@ -147,7 +176,7 @@ pqsignal(int signo, pqsigfunc func)
 		Assert(false);			/* probably indicates coding error */
 #else
 	/* Forward to Windows native signal system. */
-	if (signal(signo, func) == SIG_ERR)
+	if (signal(signo, use_wrapper ? wrapper_handler : func) == SIG_ERR)
 		Assert(false);			/* probably indicates coding error */
 #endif
 }
-- 
2.43.0



^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-06 16:51  Andrew Dunstan <andrew@dunslane.net>
  parent: Jakub Wartak <jakub.wartak@enterprisedb.com>
  0 siblings, 3 replies; 54+ messages in thread

From: Andrew Dunstan @ 2026-04-06 16:51 UTC (permalink / raw)
  To: Jakub Wartak <jakub.wartak@enterprisedb.com>; Chao Li <li.evan.chao@gmail.com>; +Cc: Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>


On 2026-02-26 Th 4:25 AM, Jakub Wartak wrote:
> On Thu, Feb 26, 2026 at 4:09 AM Chao Li <li.evan.chao@gmail.com> wrote:
>
> Hi Chao,
>
>> I just reviewed v4 again and got a few more comments:
>>
>> 1. This patch only set the global proc_die_sender_pid/uid to 0 at startup, then assign values to them upon receiving SIGTERM, and never reset them, which assumes a process must die upon SIGTERM. Is the assumption true? I guess not. If a process receives SIGTERM and not die immediately, then die for other reason, then it may report a misleading PID and UID.
> Hmm, I'm not sure I follow. If we receive SIGTERM and not die immediately
> (for whatever reason), then two scenarios can happen as far as I'm concerned:
> * another SIGTERM comes in from the same or different uid/pid and it wll be
> reported properly
> * different SIGKILL, but in this case we won't report UID/PID at all
>
> am I missing something or do You have any particular scenario in mind?
> The flow will be wrapper_handler()->die()->SetLatch()->..->directyl to
> err reporting facilities.
>
>> 2.
>> syncrpe.c uses errhint to print PID and UID, and postgres.c uses errdetail. We should keep consistency, maybe all use errhint.
> Right, let's make it that way.
>
>> 3.
>> ```
>> @@ -319,7 +323,11 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
>>                          QueryCancelPending = false;
>>                          ereport(WARNING,
>>                                          (errmsg("canceling wait for synchronous replication due to user request"),
>> -                                        errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
>> +                                        errdetail("The transaction has already committed locally, but might not have been replicated to the standby."),
>> +                                               proc_die_sender_pid == 0 ? 0 :
>> +                                                       errhint("Signal sent by PID %d, UID %d.",
>> +                                                               proc_die_sender_pid, proc_die_sender_uid)
>> +                                               ));
>>                          SyncRepCancelWait();
>>                          break;
>>                  }
>> ```
>>
>> I don’t think the query cancel case relates to SIGTERM, so we don’t need to log PID and UID here.
> Right, it was superfluous.
>
> v5 attached.
>


I'd kinda like to sneak this in for pg19, because I think it's useful. 
Here's a v6 that changes one or two things:


- changes the globals to sig_atomic_t

- in ProcessInterrupts, copies to local sender_pid/sender_uid, then 
zeros the globals before any ereport

- uses errdetail() for all the messages


Plus a few more cosmetic changes like consistent casing.


cheers


andrew



--
Andrew Dunstan
EDB: https://www.enterprisedb.com

Attachments:

  [text/x-patch] v6-0001-Add-errdetail-with-PID-and-UID-about-source-of-te.patch (12.8K, ../../1ba07c75-cc4e-410c-9af1-076feeeb9594@dunslane.net/2-v6-0001-Add-errdetail-with-PID-and-UID-about-source-of-te.patch)
  download | inline diff:
From 450b68d29f02ee1f5bf71db708b380ab389a30c6 Mon Sep 17 00:00:00 2001
From: Andrew Dunstan <andrew@dunslane.net>
Date: Mon, 6 Apr 2026 12:39:14 -0400
Subject: [PATCH v6] Add errdetail() with PID and UID about source of
 termination signal.

When a backend is terminated via pg_terminate_backend() or an external
SIGTERM, the error message now includes the sender's PID and UID as
errdetail, making it easier to identify the source of unexpected
terminations in multi-user environments.

On platforms that support SA_SIGINFO (Linux, FreeBSD, and most modern
Unix systems), the signal handler captures si_pid and si_uid from the
siginfo_t structure.  On platforms without SA_SIGINFO, the detail is
simply omitted.

Author: Jakub Wartak <jakub.wartak@enterprisedb.com>
Reviewed-by: Andrew Dunstan <andrew@dunslane.net>
Reviewed-by: Chao Li <1356863904@qq.com>
Discussion: https://postgr.es/m/CAKZiRmyrOWovZSdixpLd3PGMQXuQL_zw2Ght5XhHCkQ1uDsxjw@mail.gmail.com
---
 configure                         | 42 +++++++++++++++++++++++++++++++
 configure.ac                      | 18 +++++++++++++
 meson.build                       |  4 +++
 src/backend/replication/syncrep.c |  6 ++++-
 src/backend/tcop/postgres.c       | 26 +++++++++++++------
 src/backend/utils/init/globals.c  |  2 ++
 src/bin/psql/t/001_basic.pl       |  7 +++---
 src/include/miscadmin.h           | 10 ++++++++
 src/include/pg_config.h.in        |  3 +++
 src/port/pqsignal.c               | 35 +++++++++++++++++++++++---
 10 files changed, 138 insertions(+), 15 deletions(-)

diff --git a/configure b/configure
index c56ef60226d..f66c1054a7a 100755
--- a/configure
+++ b/configure
@@ -15797,6 +15797,48 @@ if test "$ac_cv_sizeof_off_t" -lt 8; then
   fi
 fi
 
+# Check for SA_SIGINFO extended signal handler availability
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for SA_SIGINFO" >&5
+$as_echo_n "checking for SA_SIGINFO... " >&6; }
+if ${ac_cv_have_sa_siginfo+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+
+    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+
+            #include <signal.h>
+            #include <stddef.h>
+
+int
+main ()
+{
+
+            struct sigaction sa;
+            sa.sa_flags = SA_SIGINFO;
+
+  ;
+  return 0;
+}
+
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_have_sa_siginfo=yes
+else
+  ac_cv_have_sa_siginfo=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_have_sa_siginfo" >&5
+$as_echo "$ac_cv_have_sa_siginfo" >&6; }
+
+if test "x$ac_cv_have_sa_siginfo" = "xyes"; then
+
+$as_echo "#define HAVE_SA_SIGINFO 1" >>confdefs.h
+
+fi
 
 ##
 ## Functions, global variables
diff --git a/configure.ac b/configure.ac
index ff5dd64468e..8d176bd3468 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1817,6 +1817,24 @@ if test "$ac_cv_sizeof_off_t" -lt 8; then
   fi
 fi
 
+# Check for SA_SIGINFO extended signal handler availability
+AC_CACHE_CHECK([for SA_SIGINFO], [ac_cv_have_sa_siginfo], [
+    AC_COMPILE_IFELSE([
+        AC_LANG_PROGRAM([[
+            #include <signal.h>
+            #include <stddef.h>
+        ]], [[
+            struct sigaction sa;
+            sa.sa_flags = SA_SIGINFO;
+        ]])
+    ],
+    [ac_cv_have_sa_siginfo=yes],
+    [ac_cv_have_sa_siginfo=no])
+])
+
+if test "x$ac_cv_have_sa_siginfo" = "xyes"; then
+    AC_DEFINE([HAVE_SA_SIGINFO], 1, [Define to 1 if you have SA_SIGINFO available.])
+fi
 
 ##
 ## Functions, global variables
diff --git a/meson.build b/meson.build
index 43d5ffc30b1..be97e986e5d 100644
--- a/meson.build
+++ b/meson.build
@@ -2985,6 +2985,10 @@ if cc.has_member('struct sockaddr', 'sa_len',
   cdata.set('HAVE_STRUCT_SOCKADDR_SA_LEN', 1)
 endif
 
+if cc.has_header_symbol('signal.h', 'SA_SIGINFO')
+  cdata.set('HAVE_SA_SIGINFO', 1)
+endif
+
 if cc.has_member('struct tm', 'tm_zone',
     args: test_c_args, include_directories: postgres_inc,
     prefix: '''
diff --git a/src/backend/replication/syncrep.c b/src/backend/replication/syncrep.c
index 9cecc83ed68..41a4b837688 100644
--- a/src/backend/replication/syncrep.c
+++ b/src/backend/replication/syncrep.c
@@ -303,7 +303,11 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 			ereport(WARNING,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
 					 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
+					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.%s",
+							   ProcDieSenderPid == 0 ? "" :
+							   psprintf("\nSignal sent by PID %d, UID %d.",
+										(int) ProcDieSenderPid,
+										(int) ProcDieSenderUid))));
 			whereToSendOutput = DestNone;
 			SyncRepCancelWait();
 			break;
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 10be60011ad..a53df31c989 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -3345,7 +3345,12 @@ ProcessInterrupts(void)
 
 	if (ProcDiePending)
 	{
+		int			sender_pid = ProcDieSenderPid;
+		int			sender_uid = ProcDieSenderUid;
+
 		ProcDiePending = false;
+		ProcDieSenderPid = 0;
+		ProcDieSenderUid = 0;
 		QueryCancelPending = false; /* ProcDie trumps QueryCancel */
 		LockErrorCleanup();
 		/* As in quickdie, don't risk sending to client during auth */
@@ -3358,15 +3363,18 @@ ProcessInterrupts(void)
 		else if (AmAutoVacuumWorkerProcess())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating autovacuum process due to administrator command")));
+					 errmsg("terminating autovacuum process due to administrator command"),
+					 ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
 		else if (IsLogicalWorker())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating logical replication worker due to administrator command")));
+					 errmsg("terminating logical replication worker due to administrator command"),
+					 ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
 		else if (IsLogicalLauncher())
 		{
 			ereport(DEBUG1,
-					(errmsg_internal("logical replication launcher shutting down")));
+					(errmsg_internal("logical replication launcher shutting down"),
+					 ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
 
 			/*
 			 * The logical replication launcher can be stopped at any time.
@@ -3377,23 +3385,27 @@ ProcessInterrupts(void)
 		else if (AmWalReceiverProcess())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating walreceiver process due to administrator command")));
+					 errmsg("terminating walreceiver process due to administrator command"),
+					 ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
 		else if (AmBackgroundWorkerProcess())
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
 					 errmsg("terminating background worker \"%s\" due to administrator command",
-							MyBgworkerEntry->bgw_type)));
+							MyBgworkerEntry->bgw_type),
+					 ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
 		else if (AmIoWorkerProcess())
 		{
 			ereport(DEBUG1,
-					(errmsg_internal("io worker shutting down due to administrator command")));
+					(errmsg_internal("io worker shutting down due to administrator command"),
+					 ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
 
 			proc_exit(0);
 		}
 		else
 			ereport(FATAL,
 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("terminating connection due to administrator command")));
+					 errmsg("terminating connection due to administrator command"),
+					 ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
 	}
 
 	if (CheckClientConnectionPending)
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index 36ad708b360..073f8102454 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -43,6 +43,8 @@ volatile sig_atomic_t IdleStatsUpdateTimeoutPending = false;
 volatile uint32 InterruptHoldoffCount = 0;
 volatile uint32 QueryCancelHoldoffCount = 0;
 volatile uint32 CritSectionCount = 0;
+volatile sig_atomic_t ProcDieSenderPid = 0;
+volatile sig_atomic_t ProcDieSenderUid = 0;
 
 int			MyProcPid;
 pg_time_t	MyStartTime;
diff --git a/src/bin/psql/t/001_basic.pl b/src/bin/psql/t/001_basic.pl
index 6839f27cbe5..7c21204c1f2 100644
--- a/src/bin/psql/t/001_basic.pl
+++ b/src/bin/psql/t/001_basic.pl
@@ -142,12 +142,11 @@ my ($ret, $out, $err) = $node->psql('postgres',
 is($ret, 2, 'server crash: psql exit code');
 like($out, qr/before/, 'server crash: output before crash');
 unlike($out, qr/AFTER/, 'server crash: no output after crash');
-is( $err,
-	'psql:<stdin>:2: FATAL:  terminating connection due to administrator command
-psql:<stdin>:2: server closed the connection unexpectedly
+like( $err, qr/psql:<stdin>:2: FATAL:  terminating connection due to administrator command
+(?:DETAIL:  Signal sent by PID \d+, UID \d+\.\n)?psql:<stdin>:2: server closed the connection unexpectedly
 	This probably means the server terminated abnormally
 	before or while processing the request.
-psql:<stdin>:2: error: connection to server was lost',
+psql:<stdin>:2: error: connection to server was lost/,
 	'server crash: error message');
 
 # test \errverbose
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index 7277c37e779..bc4717ab7da 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -90,6 +90,16 @@
 extern PGDLLIMPORT volatile sig_atomic_t InterruptPending;
 extern PGDLLIMPORT volatile sig_atomic_t QueryCancelPending;
 extern PGDLLIMPORT volatile sig_atomic_t ProcDiePending;
+extern PGDLLIMPORT volatile sig_atomic_t ProcDieSenderPid;
+extern PGDLLIMPORT volatile sig_atomic_t ProcDieSenderUid;
+
+/*
+ * Include signal sender PID/UID as errdetail when available (SA_SIGINFO).
+ * The caller must supply the (already-captured) pid and uid values.
+ */
+#define ERRDETAIL_SIGNAL_SENDER(pid, uid) \
+	((pid) == 0 ? 0 : \
+	 errdetail("Signal sent by PID %d, UID %d.", (int) (pid), (int) (uid)))
 extern PGDLLIMPORT volatile sig_atomic_t IdleInTransactionSessionTimeoutPending;
 extern PGDLLIMPORT volatile sig_atomic_t TransactionTimeoutPending;
 extern PGDLLIMPORT volatile sig_atomic_t IdleSessionTimeoutPending;
diff --git a/src/include/pg_config.h.in b/src/include/pg_config.h.in
index 9f6d512347e..4f8113c144b 100644
--- a/src/include/pg_config.h.in
+++ b/src/include/pg_config.h.in
@@ -354,6 +354,9 @@
 /* Define to 1 if you have the `rl_variable_bind' function. */
 #undef HAVE_RL_VARIABLE_BIND
 
+/* Define to 1 if you have SA_SIGINFO available. */
+#undef HAVE_SA_SIGINFO
+
 /* Define to 1 if you have the <security/pam_appl.h> header file. */
 #undef HAVE_SECURITY_PAM_APPL_H
 
diff --git a/src/port/pqsignal.c b/src/port/pqsignal.c
index fbdf9341c2f..8841464b5cb 100644
--- a/src/port/pqsignal.c
+++ b/src/port/pqsignal.c
@@ -82,10 +82,19 @@ static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
  *
  * This wrapper also handles restoring the value of errno.
  */
+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+static void
+wrapper_handler(int signo, siginfo_t * info, void *context)
+#else
 static void
 wrapper_handler(SIGNAL_ARGS)
+#endif
 {
 	int			save_errno = errno;
+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+	/* SA_SIGINFO signature uses signo, not SIGNAL_ARGS macro */
+	int			postgres_signal_arg = signo;
+#endif
 
 	Assert(postgres_signal_arg > 0);
 	Assert(postgres_signal_arg < PG_NSIG);
@@ -105,6 +114,14 @@ wrapper_handler(SIGNAL_ARGS)
 		raise(postgres_signal_arg);
 		return;
 	}
+
+#ifdef HAVE_SA_SIGINFO
+	if (signo == SIGTERM && info)
+	{
+		ProcDieSenderPid = info->si_pid;
+		ProcDieSenderUid = info->si_uid;
+	}
+#endif
 #endif
 
 	(*pqsignal_handlers[postgres_signal_arg]) (postgres_signal_arg);
@@ -125,6 +142,7 @@ pqsignal(int signo, pqsigfunc func)
 #if !(defined(WIN32) && defined(FRONTEND))
 	struct sigaction act;
 #endif
+	bool		use_wrapper = false;
 
 	Assert(signo > 0);
 	Assert(signo < PG_NSIG);
@@ -132,13 +150,24 @@ pqsignal(int signo, pqsigfunc func)
 	if (func != SIG_IGN && func != SIG_DFL)
 	{
 		pqsignal_handlers[signo] = func;	/* assumed atomic */
-		func = wrapper_handler;
+		use_wrapper = true;
 	}
 
 #if !(defined(WIN32) && defined(FRONTEND))
-	act.sa_handler = func;
 	sigemptyset(&act.sa_mask);
 	act.sa_flags = SA_RESTART;
+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+	if (use_wrapper)
+	{
+		act.sa_sigaction = wrapper_handler;
+		act.sa_flags |= SA_SIGINFO;
+	}
+	else
+		act.sa_handler = func;
+#else
+	act.sa_handler = use_wrapper ? wrapper_handler : func;
+#endif
+
 #ifdef SA_NOCLDSTOP
 	if (signo == SIGCHLD)
 		act.sa_flags |= SA_NOCLDSTOP;
@@ -147,7 +176,7 @@ pqsignal(int signo, pqsigfunc func)
 		Assert(false);			/* probably indicates coding error */
 #else
 	/* Forward to Windows native signal system. */
-	if (signal(signo, func) == SIG_ERR)
+	if (signal(signo, use_wrapper ? wrapper_handler : func) == SIG_ERR)
 		Assert(false);			/* probably indicates coding error */
 #endif
 }
-- 
2.43.0



^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-06 19:36  Daniel Gustafsson <daniel@yesql.se>
  parent: Andrew Dunstan <andrew@dunslane.net>
  2 siblings, 0 replies; 54+ messages in thread

From: Daniel Gustafsson @ 2026-04-06 19:36 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Jakub Wartak <jakub.wartak@enterprisedb.com>; Chao Li <li.evan.chao@gmail.com>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

> On 6 Apr 2026, at 18:51, Andrew Dunstan <andrew@dunslane.net> wrote:

> I'd kinda like to sneak this in for pg19, because I think it's useful. Here's a v6 that changes one or two things:

+1.  I haven't done an in-depth review but I quite like the feature and have
wanted this very thing in the past.

--
Daniel Gustafsson






^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-07 03:55  jie wang <jugierwang@gmail.com>
  parent: Andrew Dunstan <andrew@dunslane.net>
  2 siblings, 1 reply; 54+ messages in thread

From: jie wang @ 2026-04-07 03:55 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Jakub Wartak <jakub.wartak@enterprisedb.com>; Chao Li <li.evan.chao@gmail.com>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Andrew Dunstan <andrew@dunslane.net> 于2026年4月7日周二 00:51写道:

>
> On 2026-02-26 Th 4:25 AM, Jakub Wartak wrote:
> > On Thu, Feb 26, 2026 at 4:09 AM Chao Li <li.evan.chao@gmail.com> wrote:
> >
> > Hi Chao,
> >
> >> I just reviewed v4 again and got a few more comments:
> >>
> >> 1. This patch only set the global proc_die_sender_pid/uid to 0 at
> startup, then assign values to them upon receiving SIGTERM, and never reset
> them, which assumes a process must die upon SIGTERM. Is the assumption
> true? I guess not. If a process receives SIGTERM and not die immediately,
> then die for other reason, then it may report a misleading PID and UID.
> > Hmm, I'm not sure I follow. If we receive SIGTERM and not die immediately
> > (for whatever reason), then two scenarios can happen as far as I'm
> concerned:
> > * another SIGTERM comes in from the same or different uid/pid and it wll
> be
> > reported properly
> > * different SIGKILL, but in this case we won't report UID/PID at all
> >
> > am I missing something or do You have any particular scenario in mind?
> > The flow will be wrapper_handler()->die()->SetLatch()->..->directyl to
> > err reporting facilities.
> >
> >> 2.
> >> syncrpe.c uses errhint to print PID and UID, and postgres.c uses
> errdetail. We should keep consistency, maybe all use errhint.
> > Right, let's make it that way.
> >
> >> 3.
> >> ```
> >> @@ -319,7 +323,11 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
> >>                          QueryCancelPending = false;
> >>                          ereport(WARNING,
> >>                                          (errmsg("canceling wait for
> synchronous replication due to user request"),
> >> -                                        errdetail("The transaction has
> already committed locally, but might not have been replicated to the
> standby.")));
> >> +                                        errdetail("The transaction has
> already committed locally, but might not have been replicated to the
> standby."),
> >> +                                               proc_die_sender_pid ==
> 0 ? 0 :
> >> +                                                       errhint("Signal
> sent by PID %d, UID %d.",
> >> +
>  proc_die_sender_pid, proc_die_sender_uid)
> >> +                                               ));
> >>                          SyncRepCancelWait();
> >>                          break;
> >>                  }
> >> ```
> >>
> >> I don’t think the query cancel case relates to SIGTERM, so we don’t
> need to log PID and UID here.
> > Right, it was superfluous.
> >
> > v5 attached.
> >
>
>
> I'd kinda like to sneak this in for pg19, because I think it's useful.
> Here's a v6 that changes one or two things:
>
>
> - changes the globals to sig_atomic_t
>
> - in ProcessInterrupts, copies to local sender_pid/sender_uid, then
> zeros the globals before any ereport
>
> - uses errdetail() for all the messages
>
>
> Plus a few more cosmetic changes like consistent casing.
>
>
> cheers
>
>
> andrew
>
>
>
> --
> Andrew Dunstan
> EDB: https://www.enterprisedb.com



I just reviewed v6 and got 1 comment.

sig_atomic_t is underlying int, but pid_t and uid_t are usually unsigned
int,
so that while saving pid and uid to ProcDieSenderPid and ProcDieSenderUid,
overflow may happen. But that’s fine, as the data is stored in the same way
and we only want to print them. So, for the print statement:

#define ERRDETAIL_SIGNAL_SENDER(pid, uid) \
    ((pid) == 0 ? 0 : \
    errdetail("Signal sent by PID %d, UID %d.", (int) (pid), (int) (uid)))

Does it make sense to use %u and cast to pid_t and uid_t? Like:

#define ERRDETAIL_SIGNAL_SENDER(pid, uid) \
    ((pid) == 0 ? 0 : \
    errdetail("Signal sent by PID %u, UID %u.", (pid_t) (pid), (uid_t)
(uid)))

Thanks!
--
wang jie

^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-07 09:10  Jakub Wartak <jakub.wartak@enterprisedb.com>
  parent: jie wang <jugierwang@gmail.com>
  0 siblings, 1 reply; 54+ messages in thread

From: Jakub Wartak @ 2026-04-07 09:10 UTC (permalink / raw)
  To: jie wang <jugierwang@gmail.com>; +Cc: Andrew Dunstan <andrew@dunslane.net>; Chao Li <li.evan.chao@gmail.com>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, Apr 7, 2026 at 5:55 AM jie wang <jugierwang@gmail.com> wrote:
>
>
>
> Andrew Dunstan <andrew@dunslane.net> 于2026年4月7日周二 00:51写道:
>>
>>
[..]
>>
>> I'd kinda like to sneak this in for pg19, because I think it's useful.
>> Here's a v6 that changes one or two things:
>>
>>
>> - changes the globals to sig_atomic_t
>>
>> - in ProcessInterrupts, copies to local sender_pid/sender_uid, then
>> zeros the globals before any ereport
>>
>> - uses errdetail() for all the messages
>>
>>
>> Plus a few more cosmetic changes like consistent casing.
>>
>>
>> cheers
>>
>>
>> andrew
>>
>>
>>
>> --
>> Andrew Dunstan
>> EDB: https://www.enterprisedb.com
>
>
>
> I just reviewed v6 and got 1 comment.
>
> sig_atomic_t is underlying int, but pid_t and uid_t are usually unsigned int,
> so that while saving pid and uid to ProcDieSenderPid and ProcDieSenderUid,
> overflow may happen. But that’s fine, as the data is stored in the same way
> and we only want to print them. So, for the print statement:
>
> #define ERRDETAIL_SIGNAL_SENDER(pid, uid) \
>     ((pid) == 0 ? 0 : \
>     errdetail("Signal sent by PID %d, UID %d.", (int) (pid), (int) (uid)))
>
> Does it make sense to use %u and cast to pid_t and uid_t? Like:
>
> #define ERRDETAIL_SIGNAL_SENDER(pid, uid) \
>     ((pid) == 0 ? 0 : \
>     errdetail("Signal sent by PID %u, UID %u.", (pid_t) (pid), (uid_t) (uid)))

I really don't have hard opinion on what we should use here (int vs uint32 vs
pid_t)  and I was scratching my head at this earier, as:

1. Usually win32 doesn't have pid_t, but in win32_port.h we have
   "typedef int pid_t".

2. According to `grep -ri ' pid' src/backend/ we seem to use "int" in most cases
   for this (especially MyProcPid is also int). The only other places
where I found
   %u or %l would be those:

   src/backend/port/win32/signal.c:
        snprintf(pipename, sizeof(pipename),
"\\\\.\\pipe\\pgsignal_%u", (int) pid);

   src/backend/port/win32/signal.c:
        (errmsg("could not create signal listener pipe for PID %d:
error code %lu",
   src/backend/postmaster/datachecksum_state.c:
        "Waiting for worker in database %s (pid %ld)", db->dbname, (long) pid);
   src/backend/postmaster/postmaster.c:
        elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);

   So apparently we are really not consistent, but int looks fine to me.

3. Linux kernel for most allows up to kernel.pid_max (4194304, 22 bits) and
   internally it uses "int" for it's pid_max_max [1] and uses up to
30-bits since always.

So "int" follows old style and seems to be OK at least from my point of view.

-J.

[1] - https://github.com/torvalds/linux/blob/master/kernel/pid.c#L64C17-L64C40
[2] - https://github.com/torvalds/linux/blob/master/include/linux/threads.h#L34





^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-07 14:36  Andrew Dunstan <andrew@dunslane.net>
  parent: Jakub Wartak <jakub.wartak@enterprisedb.com>
  0 siblings, 0 replies; 54+ messages in thread

From: Andrew Dunstan @ 2026-04-07 14:36 UTC (permalink / raw)
  To: Jakub Wartak <jakub.wartak@enterprisedb.com>; jie wang <jugierwang@gmail.com>; +Cc: Chao Li <li.evan.chao@gmail.com>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>


On 2026-04-07 Tu 5:10 AM, Jakub Wartak wrote:
> On Tue, Apr 7, 2026 at 5:55 AM jie wang<jugierwang@gmail.com> wrote:
>>
>>
>> Andrew Dunstan<andrew@dunslane.net> 于2026年4月7日周二 00:51写道:
>>>
> [..]
>>> I'd kinda like to sneak this in for pg19, because I think it's useful.
>>> Here's a v6 that changes one or two things:
>>>
>>>
>>> - changes the globals to sig_atomic_t
>>>
>>> - in ProcessInterrupts, copies to local sender_pid/sender_uid, then
>>> zeros the globals before any ereport
>>>
>>> - uses errdetail() for all the messages
>>>
>>>
>>> Plus a few more cosmetic changes like consistent casing.
>>>
>>>
>>> cheers
>>>
>>>
>>> andrew
>>>
>>>
>>>
>>> --
>>> Andrew Dunstan
>>> EDB:https://www.enterprisedb.com
>>
>>
>> I just reviewed v6 and got 1 comment.
>>
>> sig_atomic_t is underlying int, but pid_t and uid_t are usually unsigned int,
>> so that while saving pid and uid to ProcDieSenderPid and ProcDieSenderUid,
>> overflow may happen. But that’s fine, as the data is stored in the same way
>> and we only want to print them. So, for the print statement:
>>
>> #define ERRDETAIL_SIGNAL_SENDER(pid, uid) \
>>      ((pid) == 0 ? 0 : \
>>      errdetail("Signal sent by PID %d, UID %d.", (int) (pid), (int) (uid)))
>>
>> Does it make sense to use %u and cast to pid_t and uid_t? Like:
>>
>> #define ERRDETAIL_SIGNAL_SENDER(pid, uid) \
>>      ((pid) == 0 ? 0 : \
>>      errdetail("Signal sent by PID %u, UID %u.", (pid_t) (pid), (uid_t) (uid)))
> I really don't have hard opinion on what we should use here (int vs uint32 vs
> pid_t)  and I was scratching my head at this earier, as:
>
> 1. Usually win32 doesn't have pid_t, but in win32_port.h we have
>     "typedef int pid_t".
>
> 2. According to `grep -ri ' pid' src/backend/ we seem to use "int" in most cases
>     for this (especially MyProcPid is also int). The only other places
> where I found
>     %u or %l would be those:
>
>     src/backend/port/win32/signal.c:
>          snprintf(pipename, sizeof(pipename),
> "\\\\.\\pipe\\pgsignal_%u", (int) pid);
>
>     src/backend/port/win32/signal.c:
>          (errmsg("could not create signal listener pipe for PID %d:
> error code %lu",
>     src/backend/postmaster/datachecksum_state.c:
>          "Waiting for worker in database %s (pid %ld)", db->dbname, (long) pid);
>     src/backend/postmaster/postmaster.c:
>          elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
>
>     So apparently we are really not consistent, but int looks fine to me.
>
> 3. Linux kernel for most allows up to kernel.pid_max (4194304, 22 bits) and
>     internally it uses "int" for it's pid_max_max [1] and uses up to
> 30-bits since always.
>
> So "int" follows old style and seems to be OK at least from my point of view.
>
> -J.
>
> [1] -https://github.com/torvalds/linux/blob/master/kernel/pid.c#L64C17-L64C40
> [2] -https://github.com/torvalds/linux/blob/master/include/linux/threads.h#L34



OK, went back to using int. Pushed.


cheers


andrew

--
Andrew Dunstan
EDB:https://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-07 14:55  Andres Freund <andres@anarazel.de>
  parent: Andrew Dunstan <andrew@dunslane.net>
  2 siblings, 1 reply; 54+ messages in thread

From: Andres Freund @ 2026-04-07 14:55 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Jakub Wartak <jakub.wartak@enterprisedb.com>; Chao Li <li.evan.chao@gmail.com>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2026-04-06 12:51:40 -0400, Andrew Dunstan wrote:
> From 450b68d29f02ee1f5bf71db708b380ab389a30c6 Mon Sep 17 00:00:00 2001
> From: Andrew Dunstan <andrew@dunslane.net>
> Date: Mon, 6 Apr 2026 12:39:14 -0400
> Subject: [PATCH v6] Add errdetail() with PID and UID about source of
>  termination signal.
>
> When a backend is terminated via pg_terminate_backend() or an external
> SIGTERM, the error message now includes the sender's PID and UID as
> errdetail, making it easier to identify the source of unexpected
> terminations in multi-user environments.
>
> On platforms that support SA_SIGINFO (Linux, FreeBSD, and most modern
> Unix systems), the signal handler captures si_pid and si_uid from the
> siginfo_t structure.  On platforms without SA_SIGINFO, the detail is
> simply omitted.
>
> Author: Jakub Wartak <jakub.wartak@enterprisedb.com>
> Reviewed-by: Andrew Dunstan <andrew@dunslane.net>
> Reviewed-by: Chao Li <1356863904@qq.com>
> Discussion: https://postgr.es/m/CAKZiRmyrOWovZSdixpLd3PGMQXuQL_zw2Ght5XhHCkQ1uDsxjw@mail.gmail.com


> +++ b/src/backend/replication/syncrep.c
> @@ -303,7 +303,11 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
>  			ereport(WARNING,
>  					(errcode(ERRCODE_ADMIN_SHUTDOWN),
>  					 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
> -					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
> +					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.%s",
> +							   ProcDieSenderPid == 0 ? "" :
> +							   psprintf("\nSignal sent by PID %d, UID %d.",
> +										(int) ProcDieSenderPid,
> +										(int) ProcDieSenderUid))));
>  			whereToSendOutput = DestNone;
>  			SyncRepCancelWait();
>  			break;

Pretty sure this is broken from a translateability POV?

It's also somewhat ugly.


> +++ b/src/port/pqsignal.c
> @@ -82,10 +82,19 @@ static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
>   *
>   * This wrapper also handles restoring the value of errno.
>   */
> +#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
> +static void
> +wrapper_handler(int signo, siginfo_t * info, void *context)
> +#else
>  static void
>  wrapper_handler(SIGNAL_ARGS)
> +#endif
>  {
>  	int			save_errno = errno;
> +#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
> +	/* SA_SIGINFO signature uses signo, not SIGNAL_ARGS macro */
> +	int			postgres_signal_arg = signo;
> +#endif

Seems that you then should change what SIGNAL_ARGS means, not randomly hack
around it in one place?


>  	Assert(postgres_signal_arg > 0);
>  	Assert(postgres_signal_arg < PG_NSIG);
> @@ -105,6 +114,14 @@ wrapper_handler(SIGNAL_ARGS)
>  		raise(postgres_signal_arg);
>  		return;
>  	}
> +
> +#ifdef HAVE_SA_SIGINFO
> +	if (signo == SIGTERM && info)
> +	{
> +		ProcDieSenderPid = info->si_pid;
> +		ProcDieSenderUid = info->si_uid;
> +	}
> +#endif
>  #endif
>
>  	(*pqsignal_handlers[postgres_signal_arg]) (postgres_signal_arg);

This seems completely wrong from a layering POV.  The wrapper has no business
whatsoever to know that how SIGTERM is interpreted and thus no business
setting variables like ProcDieSenderPid.

Pretty sure have some sigterm handlers that shouldn't set ProcDieSenderPid.


A more correct answer here would be to forward information about the sender of
a signal to the signal handlers and let them interpret the information if
available.



I think this is nowhere near ready to have been committed.


Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-07 16:49  Andrew Dunstan <andrew@dunslane.net>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 1 reply; 54+ messages in thread

From: Andrew Dunstan @ 2026-04-07 16:49 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Jakub Wartak <jakub.wartak@enterprisedb.com>; Chao Li <li.evan.chao@gmail.com>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>


On 2026-04-07 Tu 10:55 AM, Andres Freund wrote:
>
> This seems completely wrong from a layering POV.  The wrapper has no business
> whatsoever to know that how SIGTERM is interpreted and thus no business
> setting variables like ProcDieSenderPid.
>
> Pretty sure have some sigterm handlers that shouldn't set ProcDieSenderPid.
>
>
> A more correct answer here would be to forward information about the sender of
> a signal to the signal handlers and let them interpret the information if
> available.
>

OK, fair points. Does the attached meet your concerns?


cheers


andrew

--
Andrew Dunstan
EDB:https://www.enterprisedb.com

Attachments:

  [text/x-patch] errdetail-pid-fix.patch (4.8K, ../../a076e20d-fc56-4b5d-aa47-a52b4e7a5061@dunslane.net/3-errdetail-pid-fix.patch)
  download | inline diff:
diff --git a/src/backend/replication/syncrep.c b/src/backend/replication/syncrep.c
index 46a778f0917..896ba45412d 100644
--- a/src/backend/replication/syncrep.c
+++ b/src/backend/replication/syncrep.c
@@ -300,22 +300,18 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 		 */
 		if (ProcDiePending)
 		{
-			/*
-			 * ProcDieSenderPid/Uid are read directly from the globals here
-			 * rather than copied to locals first; a second SIGTERM could
-			 * change them between reads, but that is harmless because the
-			 * process is about to die anyway.  The signal sender detail is
-			 * inlined rather than using a separate errdetail() call because
-			 * it must be appended to the existing detail message.
-			 */
-			ereport(WARNING,
-					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.%s",
-							   ProcDieSenderPid == 0 ? "" :
-							   psprintf("\nSignal sent by PID %d, UID %d.",
-										(int) ProcDieSenderPid,
-										(int) ProcDieSenderUid))));
+			if (ProcDieSenderPid != 0)
+				ereport(WARNING,
+						(errcode(ERRCODE_ADMIN_SHUTDOWN),
+						 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
+						 errdetail("The transaction has already committed locally, but might not have been replicated to the standby. Signal sent by PID %d, UID %d.",
+								   (int) ProcDieSenderPid,
+								   (int) ProcDieSenderUid)));
+			else
+				ereport(WARNING,
+						(errcode(ERRCODE_ADMIN_SHUTDOWN),
+						 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
+						 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
 			whereToSendOutput = DestNone;
 			SyncRepCancelWait();
 			break;
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 4fb18741dc5..e02125e720e 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -3025,6 +3025,8 @@ die(SIGNAL_ARGS)
 	{
 		InterruptPending = true;
 		ProcDiePending = true;
+		ProcDieSenderPid = SignalSenderPid;
+		ProcDieSenderUid = SignalSenderUid;
 	}
 
 	/* for the cumulative stats system */
diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c
index ba8cd99d98d..bc517b009cb 100644
--- a/src/backend/utils/init/globals.c
+++ b/src/backend/utils/init/globals.c
@@ -43,6 +43,8 @@ volatile sig_atomic_t IdleStatsUpdateTimeoutPending = false;
 volatile uint32 InterruptHoldoffCount = 0;
 volatile uint32 QueryCancelHoldoffCount = 0;
 volatile uint32 CritSectionCount = 0;
+volatile int SignalSenderPid = 0;
+volatile int SignalSenderUid = 0;
 volatile int ProcDieSenderPid = 0;
 volatile int ProcDieSenderUid = 0;
 
diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h
index b6f625e10a6..655b42103ca 100644
--- a/src/include/miscadmin.h
+++ b/src/include/miscadmin.h
@@ -90,6 +90,8 @@
 extern PGDLLIMPORT volatile sig_atomic_t InterruptPending;
 extern PGDLLIMPORT volatile sig_atomic_t QueryCancelPending;
 extern PGDLLIMPORT volatile sig_atomic_t ProcDiePending;
+extern PGDLLIMPORT volatile int SignalSenderPid;
+extern PGDLLIMPORT volatile int SignalSenderUid;
 extern PGDLLIMPORT volatile int ProcDieSenderPid;
 extern PGDLLIMPORT volatile int ProcDieSenderUid;
 extern PGDLLIMPORT volatile sig_atomic_t IdleInTransactionSessionTimeoutPending;
diff --git a/src/port/pqsignal.c b/src/port/pqsignal.c
index 8841464b5cb..07985e704d5 100644
--- a/src/port/pqsignal.c
+++ b/src/port/pqsignal.c
@@ -84,17 +84,13 @@ static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
  */
 #if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
 static void
-wrapper_handler(int signo, siginfo_t * info, void *context)
+wrapper_handler(int postgres_signal_arg, siginfo_t *info, void *context)
 #else
 static void
 wrapper_handler(SIGNAL_ARGS)
 #endif
 {
 	int			save_errno = errno;
-#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
-	/* SA_SIGINFO signature uses signo, not SIGNAL_ARGS macro */
-	int			postgres_signal_arg = signo;
-#endif
 
 	Assert(postgres_signal_arg > 0);
 	Assert(postgres_signal_arg < PG_NSIG);
@@ -116,10 +112,21 @@ wrapper_handler(SIGNAL_ARGS)
 	}
 
 #ifdef HAVE_SA_SIGINFO
-	if (signo == SIGTERM && info)
+	/*
+	 * Record the signal sender's PID and UID so that individual signal
+	 * handlers can use them if they wish.  These are only valid for the
+	 * duration of the handler call and will be overwritten by the next
+	 * signal.
+	 */
+	if (info)
 	{
-		ProcDieSenderPid = info->si_pid;
-		ProcDieSenderUid = info->si_uid;
+		SignalSenderPid = info->si_pid;
+		SignalSenderUid = info->si_uid;
+	}
+	else
+	{
+		SignalSenderPid = 0;
+		SignalSenderUid = 0;
 	}
 #endif
 #endif


^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-07 18:19  Andres Freund <andres@anarazel.de>
  parent: Andrew Dunstan <andrew@dunslane.net>
  0 siblings, 1 reply; 54+ messages in thread

From: Andres Freund @ 2026-04-07 18:19 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Jakub Wartak <jakub.wartak@enterprisedb.com>; Chao Li <li.evan.chao@gmail.com>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2026-04-07 12:49:19 -0400, Andrew Dunstan wrote:
> On 2026-04-07 Tu 10:55 AM, Andres Freund wrote:
> > 
> > This seems completely wrong from a layering POV.  The wrapper has no business
> > whatsoever to know that how SIGTERM is interpreted and thus no business
> > setting variables like ProcDieSenderPid.
> > 
> > Pretty sure have some sigterm handlers that shouldn't set ProcDieSenderPid.
> > 
> > 
> > A more correct answer here would be to forward information about the sender of
> > a signal to the signal handlers and let them interpret the information if
> > available.
> > 
> 
> OK, fair points. Does the attached meet your concerns?

I think the extra data should be forwarded as arguments to the "real" (not
wrapper) handler, not as globals.  You can have signal handlers interrupt each
others on some platforms, which means that if you're not careful, you could
end up reading the values from the wrong signal.

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-07 21:31  Andrew Dunstan <andrew@dunslane.net>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 1 reply; 54+ messages in thread

From: Andrew Dunstan @ 2026-04-07 21:31 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Jakub Wartak <jakub.wartak@enterprisedb.com>; Chao Li <li.evan.chao@gmail.com>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>


On 2026-04-07 Tu 2:19 PM, Andres Freund wrote:
> Hi,
>
> On 2026-04-07 12:49:19 -0400, Andrew Dunstan wrote:
>> On 2026-04-07 Tu 10:55 AM, Andres Freund wrote:
>>> This seems completely wrong from a layering POV.  The wrapper has no business
>>> whatsoever to know that how SIGTERM is interpreted and thus no business
>>> setting variables like ProcDieSenderPid.
>>>
>>> Pretty sure have some sigterm handlers that shouldn't set ProcDieSenderPid.
>>>
>>>
>>> A more correct answer here would be to forward information about the sender of
>>> a signal to the signal handlers and let them interpret the information if
>>> available.
>>>
>> OK, fair points. Does the attached meet your concerns?
> I think the extra data should be forwarded as arguments to the "real" (not
> wrapper) handler, not as globals.  You can have signal handlers interrupt each
> others on some platforms, which means that if you're not careful, you could
> end up reading the values from the wrong signal.


OK, maybe this, then? It saves the siginfo before calling the handler, 
and restores it after the call, so you should always be looking at the 
right one.


cheers


andrew


--
Andrew Dunstan
EDB: https://www.enterprisedb.com

Attachments:

  [text/x-patch] errdetail-pid-fix2.patch (6.8K, ../../9179378a-42db-4315-9ff6-b849ad5eefaf@dunslane.net/2-errdetail-pid-fix2.patch)
  download | inline diff:
diff --git a/src/backend/replication/syncrep.c b/src/backend/replication/syncrep.c
index 46a778f0917..896ba45412d 100644
--- a/src/backend/replication/syncrep.c
+++ b/src/backend/replication/syncrep.c
@@ -300,22 +300,18 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 		 */
 		if (ProcDiePending)
 		{
-			/*
-			 * ProcDieSenderPid/Uid are read directly from the globals here
-			 * rather than copied to locals first; a second SIGTERM could
-			 * change them between reads, but that is harmless because the
-			 * process is about to die anyway.  The signal sender detail is
-			 * inlined rather than using a separate errdetail() call because
-			 * it must be appended to the existing detail message.
-			 */
-			ereport(WARNING,
-					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.%s",
-							   ProcDieSenderPid == 0 ? "" :
-							   psprintf("\nSignal sent by PID %d, UID %d.",
-										(int) ProcDieSenderPid,
-										(int) ProcDieSenderUid))));
+			if (ProcDieSenderPid != 0)
+				ereport(WARNING,
+						(errcode(ERRCODE_ADMIN_SHUTDOWN),
+						 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
+						 errdetail("The transaction has already committed locally, but might not have been replicated to the standby. Signal sent by PID %d, UID %d.",
+								   (int) ProcDieSenderPid,
+								   (int) ProcDieSenderUid)));
+			else
+				ereport(WARNING,
+						(errcode(ERRCODE_ADMIN_SHUTDOWN),
+						 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
+						 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
 			whereToSendOutput = DestNone;
 			SyncRepCancelWait();
 			break;
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 4fb18741dc5..df336e3f194 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -3023,8 +3023,16 @@ die(SIGNAL_ARGS)
 	/* Don't joggle the elbow of proc_exit */
 	if (!proc_exit_inprogress)
 	{
+		int			sender_pid = 0;
+		int			sender_uid = 0;
+
 		InterruptPending = true;
 		ProcDiePending = true;
+#ifdef HAVE_SA_SIGINFO
+		pqsignal_get_sender(&sender_pid, &sender_uid);
+#endif
+		ProcDieSenderPid = sender_pid;
+		ProcDieSenderUid = sender_uid;
 	}
 
 	/* for the cumulative stats system */
diff --git a/src/bin/psql/t/001_basic.pl b/src/bin/psql/t/001_basic.pl
index 7c21204c1f2..9d966c7bece 100644
--- a/src/bin/psql/t/001_basic.pl
+++ b/src/bin/psql/t/001_basic.pl
@@ -142,8 +142,11 @@ my ($ret, $out, $err) = $node->psql('postgres',
 is($ret, 2, 'server crash: psql exit code');
 like($out, qr/before/, 'server crash: output before crash');
 unlike($out, qr/AFTER/, 'server crash: no output after crash');
+my $detail_re = check_pg_config("#define HAVE_SA_SIGINFO 1")
+	? qr/DETAIL:  Signal sent by PID \d+, UID \d+\.\n/
+	: qr//;
 like( $err, qr/psql:<stdin>:2: FATAL:  terminating connection due to administrator command
-(?:DETAIL:  Signal sent by PID \d+, UID \d+\.\n)?psql:<stdin>:2: server closed the connection unexpectedly
+${detail_re}psql:<stdin>:2: server closed the connection unexpectedly
 	This probably means the server terminated abnormally
 	before or while processing the request.
 psql:<stdin>:2: error: connection to server was lost/,
diff --git a/src/include/libpq/pqsignal.h b/src/include/libpq/pqsignal.h
index 9f494a1fdf9..40ed553cdf6 100644
--- a/src/include/libpq/pqsignal.h
+++ b/src/include/libpq/pqsignal.h
@@ -51,4 +51,8 @@ extern PGDLLIMPORT sigset_t StartupBlockSig;
 
 extern void pqinitmask(void);
 
+#ifdef HAVE_SA_SIGINFO
+extern void pqsignal_get_sender(int *sender_pid, int *sender_uid);
+#endif
+
 #endif							/* PQSIGNAL_H */
diff --git a/src/port/pqsignal.c b/src/port/pqsignal.c
index 8841464b5cb..7ee101517aa 100644
--- a/src/port/pqsignal.c
+++ b/src/port/pqsignal.c
@@ -71,6 +71,16 @@ StaticAssertDecl(SIGALRM < PG_NSIG, "SIGALRM >= PG_NSIG");
 
 static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
 
+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+/*
+ * Pointer to the siginfo_t for the signal currently being handled.  This
+ * lives on wrapper_handler's stack frame and is saved/restored around the
+ * call to the real handler, so nested signals each see their own siginfo.
+ * Signal handlers can call pqsignal_get_sender() to retrieve it.
+ */
+static volatile siginfo_t *current_siginfo;
+#endif
+
 /*
  * Except when called with SIG_IGN or SIG_DFL, pqsignal() sets up this function
  * as the handler for all signals.  This wrapper handler function checks that
@@ -84,7 +94,7 @@ static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
  */
 #if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
 static void
-wrapper_handler(int signo, siginfo_t * info, void *context)
+wrapper_handler(int postgres_signal_arg, siginfo_t *info, void *context)
 #else
 static void
 wrapper_handler(SIGNAL_ARGS)
@@ -92,8 +102,7 @@ wrapper_handler(SIGNAL_ARGS)
 {
 	int			save_errno = errno;
 #if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
-	/* SA_SIGINFO signature uses signo, not SIGNAL_ARGS macro */
-	int			postgres_signal_arg = signo;
+	volatile siginfo_t *saved_siginfo = current_siginfo;
 #endif
 
 	Assert(postgres_signal_arg > 0);
@@ -116,19 +125,50 @@ wrapper_handler(SIGNAL_ARGS)
 	}
 
 #ifdef HAVE_SA_SIGINFO
-	if (signo == SIGTERM && info)
-	{
-		ProcDieSenderPid = info->si_pid;
-		ProcDieSenderUid = info->si_uid;
-	}
-#endif
+	current_siginfo = info;
+	(*pqsignal_handlers[postgres_signal_arg]) (postgres_signal_arg);
+	current_siginfo = saved_siginfo;
+#else
+	(*pqsignal_handlers[postgres_signal_arg]) (postgres_signal_arg);
 #endif
 
+#else							/* FRONTEND */
 	(*pqsignal_handlers[postgres_signal_arg]) (postgres_signal_arg);
+#endif
 
 	errno = save_errno;
 }
 
+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+/*
+ * pqsignal_get_sender - retrieve the PID and UID of the current signal sender
+ *
+ * This may only be called from within a signal handler.  The values come from
+ * the siginfo_t passed by the kernel to wrapper_handler, which is on the
+ * stack and thus safe against nesting: if a different signal interrupts, its
+ * wrapper_handler invocation saves and restores the pointer, so the outer
+ * handler still sees the correct siginfo after the nested handler returns.
+ *
+ * If siginfo is not available (e.g. info was NULL), returns zeros.
+ */
+void
+pqsignal_get_sender(int *sender_pid, int *sender_uid)
+{
+	volatile siginfo_t *info = current_siginfo;
+
+	if (info)
+	{
+		*sender_pid = info->si_pid;
+		*sender_uid = info->si_uid;
+	}
+	else
+	{
+		*sender_pid = 0;
+		*sender_uid = 0;
+	}
+}
+#endif
+
 /*
  * Set up a signal handler, with SA_RESTART, for signal "signo"
  *


^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-07 22:56  Andres Freund <andres@anarazel.de>
  parent: Andrew Dunstan <andrew@dunslane.net>
  0 siblings, 1 reply; 54+ messages in thread

From: Andres Freund @ 2026-04-07 22:56 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Jakub Wartak <jakub.wartak@enterprisedb.com>; Chao Li <li.evan.chao@gmail.com>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2026-04-07 17:31:18 -0400, Andrew Dunstan wrote:
> On 2026-04-07 Tu 2:19 PM, Andres Freund wrote:
> > On 2026-04-07 12:49:19 -0400, Andrew Dunstan wrote:
> > > On 2026-04-07 Tu 10:55 AM, Andres Freund wrote:
> > > > This seems completely wrong from a layering POV.  The wrapper has no business
> > > > whatsoever to know that how SIGTERM is interpreted and thus no business
> > > > setting variables like ProcDieSenderPid.
> > > > 
> > > > Pretty sure have some sigterm handlers that shouldn't set ProcDieSenderPid.
> > > > 
> > > > 
> > > > A more correct answer here would be to forward information about the sender of
> > > > a signal to the signal handlers and let them interpret the information if
> > > > available.
> > > > 
> > > OK, fair points. Does the attached meet your concerns?
> > I think the extra data should be forwarded as arguments to the "real" (not
> > wrapper) handler, not as globals.  You can have signal handlers interrupt each
> > others on some platforms, which means that if you're not careful, you could
> > end up reading the values from the wrong signal.
> 
> 
> OK, maybe this, then? It saves the siginfo before calling the handler, and
> restores it after the call, so you should always be looking at the right
> one.

I don't think that addresses my concerns at all unfortunately.  I can give
writing a sketch of how I think it should like a go, but it won't be today and
probably not this week.

I suspect this patch just has missed the boat for 19, but if others think we
can fix it up in a week or two, I'm also ok. It's a feature I wanted for a
long time.

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-08 01:03  Chao Li <li.evan.chao@gmail.com>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 1 reply; 54+ messages in thread

From: Chao Li @ 2026-04-08 01:03 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Andrew Dunstan <andrew@dunslane.net>; Jakub Wartak <jakub.wartak@enterprisedb.com>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>



> On Apr 8, 2026, at 06:56, Andres Freund <andres@anarazel.de> wrote:
> 
> Hi,
> 
> On 2026-04-07 17:31:18 -0400, Andrew Dunstan wrote:
>> On 2026-04-07 Tu 2:19 PM, Andres Freund wrote:
>>> On 2026-04-07 12:49:19 -0400, Andrew Dunstan wrote:
>>>> On 2026-04-07 Tu 10:55 AM, Andres Freund wrote:
>>>>> This seems completely wrong from a layering POV.  The wrapper has no business
>>>>> whatsoever to know that how SIGTERM is interpreted and thus no business
>>>>> setting variables like ProcDieSenderPid.
>>>>> 
>>>>> Pretty sure have some sigterm handlers that shouldn't set ProcDieSenderPid.
>>>>> 
>>>>> 
>>>>> A more correct answer here would be to forward information about the sender of
>>>>> a signal to the signal handlers and let them interpret the information if
>>>>> available.
>>>>> 
>>>> OK, fair points. Does the attached meet your concerns?
>>> I think the extra data should be forwarded as arguments to the "real" (not
>>> wrapper) handler, not as globals.  You can have signal handlers interrupt each
>>> others on some platforms, which means that if you're not careful, you could
>>> end up reading the values from the wrong signal.
>> 
>> 
>> OK, maybe this, then? It saves the siginfo before calling the handler, and
>> restores it after the call, so you should always be looking at the right
>> one.
> 
> I don't think that addresses my concerns at all unfortunately.  I can give
> writing a sketch of how I think it should like a go, but it won't be today and
> probably not this week.
> 
> I suspect this patch just has missed the boat for 19, but if others think we
> can fix it up in a week or two, I'm also ok. It's a feature I wanted for a
> long time.
> 
> Greetings,
> 
> Andres Freund

I tried to understand the layering comment, and I’m proposing a fix where sender information is stored within pqsignal and exposed via a new helper function, pqsignal_get_sender(). Then the signal handler retrieves the signal sender via pqsignal_get_sender() and sets ProcDieSenderPid/ProcDieSenderUid. Please see the attached diff.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/

Attachments:

  [application/octet-stream] errdetail-pid-fix3.diff (4.9K, ../../71930E58-82A8-4DDC-BA8C-5E394331E463@gmail.com/2-errdetail-pid-fix3.diff)
  download | inline diff:
diff --git a/src/backend/replication/syncrep.c b/src/backend/replication/syncrep.c
index 46a778f0917..73450fe437e 100644
--- a/src/backend/replication/syncrep.c
+++ b/src/backend/replication/syncrep.c
@@ -300,22 +300,18 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 		 */
 		if (ProcDiePending)
 		{
-			/*
-			 * ProcDieSenderPid/Uid are read directly from the globals here
-			 * rather than copied to locals first; a second SIGTERM could
-			 * change them between reads, but that is harmless because the
-			 * process is about to die anyway.  The signal sender detail is
-			 * inlined rather than using a separate errdetail() call because
-			 * it must be appended to the existing detail message.
-			 */
-			ereport(WARNING,
-					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.%s",
-							   ProcDieSenderPid == 0 ? "" :
-							   psprintf("\nSignal sent by PID %d, UID %d.",
-										(int) ProcDieSenderPid,
-										(int) ProcDieSenderUid))));
+			if (ProcDieSenderPid != 0)
+				ereport(WARNING,
+						(errcode(ERRCODE_ADMIN_SHUTDOWN),
+						 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
+						 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.  Signal sent by PID %d, UID %d.",
+								   (int) ProcDieSenderPid,
+								   (int) ProcDieSenderUid)));
+			else
+				ereport(WARNING,
+						(errcode(ERRCODE_ADMIN_SHUTDOWN),
+						 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
+						 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
 			whereToSendOutput = DestNone;
 			SyncRepCancelWait();
 			break;
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 14a061599bc..a9140492dcb 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -3024,6 +3024,20 @@ die(SIGNAL_ARGS)
 	/* Don't joggle the elbow of proc_exit */
 	if (!proc_exit_inprogress)
 	{
+		int			sender_pid;
+		int			sender_uid;
+
+		if (pqsignal_get_sender(postgres_signal_arg, &sender_pid, &sender_uid))
+		{
+			ProcDieSenderPid = sender_pid;
+			ProcDieSenderUid = sender_uid;
+		}
+		else
+		{
+			ProcDieSenderPid = 0;
+			ProcDieSenderUid = 0;
+		}
+
 		InterruptPending = true;
 		ProcDiePending = true;
 	}
diff --git a/src/include/libpq/pqsignal.h b/src/include/libpq/pqsignal.h
index 9f494a1fdf9..2ca32aee59e 100644
--- a/src/include/libpq/pqsignal.h
+++ b/src/include/libpq/pqsignal.h
@@ -50,5 +50,8 @@ extern PGDLLIMPORT sigset_t BlockSig;
 extern PGDLLIMPORT sigset_t StartupBlockSig;
 
 extern void pqinitmask(void);
+#ifndef FRONTEND
+extern bool pqsignal_get_sender(int signo, int *sender_pid, int *sender_uid);
+#endif
 
 #endif							/* PQSIGNAL_H */
diff --git a/src/port/pqsignal.c b/src/port/pqsignal.c
index 8841464b5cb..8cb609e58d8 100644
--- a/src/port/pqsignal.c
+++ b/src/port/pqsignal.c
@@ -70,6 +70,11 @@ StaticAssertDecl(SIGTERM < PG_NSIG, "SIGTERM >= PG_NSIG");
 StaticAssertDecl(SIGALRM < PG_NSIG, "SIGALRM >= PG_NSIG");
 
 static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+static volatile sig_atomic_t pqsignal_has_sender[PG_NSIG];
+static volatile sig_atomic_t pqsignal_sender_pid[PG_NSIG];
+static volatile sig_atomic_t pqsignal_sender_uid[PG_NSIG];
+#endif
 
 /*
  * Except when called with SIG_IGN or SIG_DFL, pqsignal() sets up this function
@@ -116,16 +121,22 @@ wrapper_handler(SIGNAL_ARGS)
 	}
 
 #ifdef HAVE_SA_SIGINFO
-	if (signo == SIGTERM && info)
+	if (info)
 	{
-		ProcDieSenderPid = info->si_pid;
-		ProcDieSenderUid = info->si_uid;
+		pqsignal_has_sender[postgres_signal_arg] = 1;
+		pqsignal_sender_pid[postgres_signal_arg] = info->si_pid;
+		pqsignal_sender_uid[postgres_signal_arg] = info->si_uid;
 	}
+	else
+		pqsignal_has_sender[postgres_signal_arg] = 0;
 #endif
 #endif
 
 	(*pqsignal_handlers[postgres_signal_arg]) (postgres_signal_arg);
 
+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+	pqsignal_has_sender[postgres_signal_arg] = 0;
+#endif
 	errno = save_errno;
 }
 
@@ -180,3 +191,25 @@ pqsignal(int signo, pqsigfunc func)
 		Assert(false);			/* probably indicates coding error */
 #endif
 }
+
+/*
+ * Return sender PID/UID for currently-dispatched signal if available.
+ */
+#ifndef FRONTEND
+bool
+pqsignal_get_sender(int signo, int *sender_pid, int *sender_uid)
+{
+#ifdef HAVE_SA_SIGINFO
+	if (signo <= 0 || signo >= PG_NSIG || !pqsignal_has_sender[signo])
+		return false;
+
+	if (sender_pid)
+		*sender_pid = (int) pqsignal_sender_pid[signo];
+	if (sender_uid)
+		*sender_uid = (int) pqsignal_sender_uid[signo];
+	return true;
+#else
+	return false;
+#endif
+}
+#endif

^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-08 09:13  Jim Jones <jim.jones@uni-muenster.de>
  parent: Chao Li <li.evan.chao@gmail.com>
  0 siblings, 1 reply; 54+ messages in thread

From: Jim Jones @ 2026-04-08 09:13 UTC (permalink / raw)
  To: Chao Li <li.evan.chao@gmail.com>; Andres Freund <andres@anarazel.de>; +Cc: Andrew Dunstan <andrew@dunslane.net>; Jakub Wartak <jakub.wartak@enterprisedb.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi

On 08/04/2026 03:03, Chao Li wrote:
> I tried to understand the layering comment, and I’m proposing a fix where sender information is stored within pqsignal and exposed via a new helper function, pqsignal_get_sender(). Then the signal handler retrieves the signal sender via pqsignal_get_sender() and sets ProcDieSenderPid/ProcDieSenderUid. Please see the attached diff.

I have a few questions (slightly unrelated to Chao's fix)

I'm a bit confused with the data flow and the data types involved:

1) in pgsignal.c it's volatile sig_atomic_t

#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
static volatile sig_atomic_t pqsignal_has_sender[PG_NSIG];
static volatile sig_atomic_t pqsignal_sender_pid[PG_NSIG];
static volatile sig_atomic_t pqsignal_sender_uid[PG_NSIG];
#endif

2) in postgres.c it's int

int  sender_pid;
int  sender_uid;

3) and in globals.c it is volatile int

volatile int ProcDieSenderPid = 0;
volatile int ProcDieSenderUid = 0;

I guess 2) is ok, since it seems to be a one time read, but I'm
wondering if the consumer in 3) should also use volatile sig_atomic_t:

in globals.c
volatile sig_atomic_t ProcDieSenderPid = 0;
volatile sig_atomic_t ProcDieSenderUid = 0;

in miscadmin.h
extern PGDLLIMPORT volatile sig_atomic_t ProcDieSenderPid;
extern PGDLLIMPORT volatile sig_atomic_t ProcDieSenderUid;


If I understood this thread correctly, the feature (v6) introduced a
problematic dual signature for wrapper_handler in pgsignal.c:

+#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+static void
+wrapper_handler(int signo, siginfo_t * info, void *context)
+#else
 static void
 wrapper_handler(SIGNAL_ARGS)
+#endif

.. and it should be rather done in the source (c.h) where SIGNAL_ARGS is
defined:

#ifndef SIGNAL_ARGS
#define SIGNAL_ARGS  int postgres_signal_arg
#endif

Something like:

#ifndef SIGNAL_ARGS
#ifdef HAVE_SA_SIGINFO
#define SIGNAL_ARGS  int postgres_signal_arg, siginfo_t
*postgres_signal_info, void *postgres_signal_context
#else
#define SIGNAL_ARGS  int postgres_signal_arg
#endif
#endif

But wouldn't it mean that all handlers need to be updated as well, since
they'd get new parameters? If this is the case, the change can be quite
substantial.

Best, Jim






^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-08 17:01  Andres Freund <andres@anarazel.de>
  parent: Jim Jones <jim.jones@uni-muenster.de>
  0 siblings, 2 replies; 54+ messages in thread

From: Andres Freund @ 2026-04-08 17:01 UTC (permalink / raw)
  To: Jim Jones <jim.jones@uni-muenster.de>; +Cc: Chao Li <li.evan.chao@gmail.com>; Andrew Dunstan <andrew@dunslane.net>; Jakub Wartak <jakub.wartak@enterprisedb.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi,

Attached is a very rough first draft for how I think this needs to look like.

Basically, SIGNAL_INFO always will pass both the signal number and extended
information along to the signal handler. The extended information is a
postgres specific struct. If the platform can't provide the extended
information, the values are instead set to some default value indicating that
the information is not known.

With that die() (and also StatementCancelHandler, ...) can just set whatever
globals it wants, without pqsignal.c needing to know about it.

It also allows us to extend the amount of information in the future. E.g. I'd
like to log the reason for a segfault (could e.g. be an OOM kill or an umapped
region) to stderr.

The annoying thing about it is needing to change nearly all the existing
references to SIG_IGN/SIG_DFL, to avoid warnings due to mismatched types.


On 2026-04-08 11:13:40 +0200, Jim Jones wrote:
> If I understood this thread correctly, the feature (v6) introduced a
> problematic dual signature for wrapper_handler in pgsignal.c:

> +#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
> +static void
> +wrapper_handler(int signo, siginfo_t * info, void *context)
> +#else
>  static void
>  wrapper_handler(SIGNAL_ARGS)
> +#endif

I think it's not a problem for wrapper_handler to change its signature, that's
a local implementation detail.  The problem is that the way the arguments were
passed was just wrong.  Because signal handlers can be nested and such
nastiness, doing any of that via global variables is a recipe for disaster.
It's also just ugly.


> .. and it should be rather done in the source (c.h) where SIGNAL_ARGS is
> defined:
> 
> #ifndef SIGNAL_ARGS
> #define SIGNAL_ARGS  int postgres_signal_arg
> #endif
> 
> Something like:
> 
> #ifndef SIGNAL_ARGS
> #ifdef HAVE_SA_SIGINFO
> #define SIGNAL_ARGS  int postgres_signal_arg, siginfo_t
> *postgres_signal_info, void *postgres_signal_context
> #else
> #define SIGNAL_ARGS  int postgres_signal_arg
> #endif
> #endif
> 
> But wouldn't it mean that all handlers need to be updated as well, since
> they'd get new parameters?

All the signal handlers actually use SIGNAL_ARGS themselves, so that part is
not a problem.

However, if we did it like you sketch above, they'd all need ifdefs etc to be
able to access any extended information, which seems like a terrible
idea. Especially if we want this information on multiple platforms, where the
struct to be passed would differ.

Hence in my prototype it's hidden behind a platform indepenedent struct of our
own.


> If this is the case, the change can be quite substantial.

It's a bit annoying to do all the s/\b(SIG_(IGN|DFL)/PG_$1/, but it's not that
bad, I think?

I unfortunately don't see a good other way to deal with it.  We could have a
macro wrapper around pqsignal() that checks for SIG_IGN with a cast to the
system type, but that seems exceedingly ugly.

Greetings,

Andres Freund

Attachments:

  [text/x-diff] v1-0001-WIP-Support-for-extended-information-about-signal.patch (29.3K, ../../jygesyr7mwg7ovdbxpmjvvbi3hccptpkcreqb645h7f56puwbz@hmkkwi3melfe/2-v1-0001-WIP-Support-for-extended-information-about-signal.patch)
  download | inline diff:
From 4e0ae1e6132ced32ec08cc219bbc8561510e3d92 Mon Sep 17 00:00:00 2001
From: Andres Freund <andres@anarazel.de>
Date: Wed, 8 Apr 2026 12:43:22 -0400
Subject: [PATCH v1] WIP: Support for extended information about signals

Author:
Reviewed-by:
Discussion: https://postgr.es/m/
Backpatch-through:
---
 src/include/c.h                             | 27 +++++---
 src/include/port.h                          |  3 +
 src/port/pqsignal.c                         | 76 ++++++++++++++-------
 src/backend/bootstrap/bootstrap.c           |  8 +--
 src/backend/postmaster/autovacuum.c         | 10 +--
 src/backend/postmaster/bgworker.c           | 14 ++--
 src/backend/postmaster/bgwriter.c           | 10 +--
 src/backend/postmaster/checkpointer.c       |  8 +--
 src/backend/postmaster/datachecksum_state.c |  2 +-
 src/backend/postmaster/pgarch.c             |  8 +--
 src/backend/postmaster/postmaster.c         | 12 ++--
 src/backend/postmaster/startup.c            |  6 +-
 src/backend/postmaster/syslogger.c          | 14 ++--
 src/backend/postmaster/walsummarizer.c      | 10 +--
 src/backend/postmaster/walwriter.c          | 10 +--
 src/backend/replication/logical/slotsync.c  |  6 +-
 src/backend/replication/walreceiver.c       | 10 +--
 src/backend/replication/walsender.c         |  4 +-
 src/backend/storage/aio/method_worker.c     |  6 +-
 src/backend/storage/file/fd.c               |  4 +-
 src/backend/storage/ipc/waiteventset.c      |  2 +-
 src/backend/tcop/postgres.c                 | 17 +++--
 src/fe_utils/print.c                        |  4 +-
 src/bin/initdb/initdb.c                     |  4 +-
 src/bin/pg_ctl/pg_ctl.c                     |  2 +-
 src/bin/pg_dump/parallel.c                  |  8 +--
 src/interfaces/libpq/legacy-pqsignal.c      |  8 ++-
 src/test/regress/pg_regress.c               |  2 +-
 src/tools/pgindent/typedefs.list            |  1 +
 29 files changed, 174 insertions(+), 122 deletions(-)

diff --git a/src/include/c.h b/src/include/c.h
index 88d13ec9993..77ea73cc707 100644
--- a/src/include/c.h
+++ b/src/include/c.h
@@ -1441,17 +1441,26 @@ extern int	fdatasync(int fd);
 #endif
 
 /*
- * The following is used as the arg list for signal handlers.  Any ports
- * that take something other than an int argument should override this in
- * their pg_config_os.h file.  Note that variable names are required
- * because it is used in both the prototypes as well as the definitions.
- * Note also the long name.  We expect that this won't collide with
- * other names causing compiler warnings.
+ * Platform independent struct representing additional information about the
+ * received signal.  If the system does not support the extended information,
+ * or a field does not apply to the signal, the value is instead reset to the
+ * documented default value.
  */
+typedef struct pg_signal_info
+{
+	pid_t		pid;			/* pid of sending process or 0 if unknown */
+	uid_t		uid;			/* uid of sending process or 0 if unknown */
+} pg_signal_info;
 
-#ifndef SIGNAL_ARGS
-#define SIGNAL_ARGS  int postgres_signal_arg
-#endif
+/*
+ * The following is used as the arg list for signal handlers. These days we
+ * use the same argument to all signal handlers and hide the difference
+ * between platforms in wrapper functions.
+ *
+ * SIGNAL_ARGS just exists separately from the pqsignal() definition for
+ * historical reasons.
+ */
+#define SIGNAL_ARGS  int postgres_signal_arg, pg_signal_info *pg_siginfo
 
 /*
  * When there is no sigsetjmp, its functionality is provided by plain
diff --git a/src/include/port.h b/src/include/port.h
index 51df9b80e7d..7db476d7b01 100644
--- a/src/include/port.h
+++ b/src/include/port.h
@@ -546,6 +546,9 @@ extern int	pg_mkdir_p(char *path, int omode);
 #else
 #define pqsignal pqsignal_be
 #endif
+
+#define PG_SIG_DFL (pqsigfunc) SIG_DFL
+#define PG_SIG_IGN (pqsigfunc) SIG_IGN
 typedef void (*pqsigfunc) (SIGNAL_ARGS);
 extern void pqsignal(int signo, pqsigfunc func);
 
diff --git a/src/port/pqsignal.c b/src/port/pqsignal.c
index 8841464b5cb..a5b32ec3945 100644
--- a/src/port/pqsignal.c
+++ b/src/port/pqsignal.c
@@ -63,6 +63,15 @@
 #define PG_NSIG (64)			/* XXX: wild guess */
 #endif
 
+#if !(defined(WIN32) && defined(FRONTEND))
+#define USE_SIGACTION
+#endif
+
+#if defined(USE_SIGACTION) && defined(HAVE_SA_SIGINFO)
+#define USE_SIGINFO
+#endif
+
+
 /* Check a couple of common signals to make sure PG_NSIG is accurate. */
 StaticAssertDecl(SIGUSR2 < PG_NSIG, "SIGUSR2 >= PG_NSIG");
 StaticAssertDecl(SIGHUP < PG_NSIG, "SIGHUP >= PG_NSIG");
@@ -82,19 +91,16 @@ static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
  *
  * This wrapper also handles restoring the value of errno.
  */
-#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+#ifdef USE_SIGACTION
 static void
-wrapper_handler(int signo, siginfo_t * info, void *context)
+wrapper_handler(int postgres_signal_arg, siginfo_t * info, void *context)
 #else
 static void
-wrapper_handler(SIGNAL_ARGS)
+wrapper_handler(int postgres_signal_arg)
 #endif
 {
 	int			save_errno = errno;
-#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
-	/* SA_SIGINFO signature uses signo, not SIGNAL_ARGS macro */
-	int			postgres_signal_arg = signo;
-#endif
+	pg_signal_info pg_info;
 
 	Assert(postgres_signal_arg > 0);
 	Assert(postgres_signal_arg < PG_NSIG);
@@ -110,21 +116,32 @@ wrapper_handler(SIGNAL_ARGS)
 
 	if (unlikely(MyProcPid != (int) getpid()))
 	{
-		pqsignal(postgres_signal_arg, SIG_DFL);
+		pqsignal(postgres_signal_arg, PG_SIG_DFL);
 		raise(postgres_signal_arg);
 		return;
 	}
+#endif
 
 #ifdef HAVE_SA_SIGINFO
-	if (signo == SIGTERM && info)
-	{
-		ProcDieSenderPid = info->si_pid;
-		ProcDieSenderUid = info->si_uid;
-	}
-#endif
+
+	/*
+	 * If supported by the system, forward interesting information from the
+	 * system's extended signal information to our platform independent
+	 * format.
+	 */
+	pg_info.pid = info->si_pid;
+	pg_info.uid = info->si_uid;
+#else
+
+	/*
+	 * Otherwise forward values indicating that we do not have the
+	 * information.
+	 */
+	pg_info.pid = 0;
+	pg_info.uid = 0;
 #endif
 
-	(*pqsignal_handlers[postgres_signal_arg]) (postgres_signal_arg);
+	(*pqsignal_handlers[postgres_signal_arg]) (postgres_signal_arg, &pg_info);
 
 	errno = save_errno;
 }
@@ -139,33 +156,44 @@ wrapper_handler(SIGNAL_ARGS)
 void
 pqsignal(int signo, pqsigfunc func)
 {
-#if !(defined(WIN32) && defined(FRONTEND))
+#ifdef USE_SIGACTION
 	struct sigaction act;
 #endif
-	bool		use_wrapper = false;
+	bool		is_ign = func == PG_SIG_IGN;
+	bool		is_dfl = func == PG_SIG_DFL;
 
 	Assert(signo > 0);
 	Assert(signo < PG_NSIG);
 
-	if (func != SIG_IGN && func != SIG_DFL)
+	/* set up indirection handler */
+	if (!(is_ign || is_dfl))
 	{
 		pqsignal_handlers[signo] = func;	/* assumed atomic */
-		use_wrapper = true;
 	}
 
-#if !(defined(WIN32) && defined(FRONTEND))
+	/*
+	 * Configure system to either ignore/reset the signal handler, or to
+	 * forward it to wrapper_handler.
+	 */
+#ifdef USE_SIGACTION
 	sigemptyset(&act.sa_mask);
 	act.sa_flags = SA_RESTART;
-#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
-	if (use_wrapper)
+
+	if (is_ign)
+		act.sa_handler = SIG_IGN;
+	else if (is_dfl)
+		act.sa_handler = SIG_DFL;
+
+#ifdef USE_SIGINFO
+	if (!(is_ign || is_dfl))
 	{
 		act.sa_sigaction = wrapper_handler;
 		act.sa_flags |= SA_SIGINFO;
 	}
 	else
-		act.sa_handler = func;
 #else
-	act.sa_handler = use_wrapper ? wrapper_handler : func;
+	else
+		act.sa_handler = wrapper_handler;
 #endif
 
 #ifdef SA_NOCLDSTOP
diff --git a/src/backend/bootstrap/bootstrap.c b/src/backend/bootstrap/bootstrap.c
index a4af7bf8fad..b0dcd9876c5 100644
--- a/src/backend/bootstrap/bootstrap.c
+++ b/src/backend/bootstrap/bootstrap.c
@@ -463,10 +463,10 @@ bootstrap_signals(void)
 	 * mode; "curl up and die" is a sufficient response for all these cases.
 	 * Let's set that handling explicitly, as documentation if nothing else.
 	 */
-	pqsignal(SIGHUP, SIG_DFL);
-	pqsignal(SIGINT, SIG_DFL);
-	pqsignal(SIGTERM, SIG_DFL);
-	pqsignal(SIGQUIT, SIG_DFL);
+	pqsignal(SIGHUP, PG_SIG_DFL);
+	pqsignal(SIGINT, PG_SIG_DFL);
+	pqsignal(SIGTERM, PG_SIG_DFL);
+	pqsignal(SIGQUIT, PG_SIG_DFL);
 }
 
 /* ----------------------------------------------------------------
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..2a87d26aa6f 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -445,11 +445,11 @@ AutoVacLauncherMain(const void *startup_data, size_t startup_data_len)
 
 	InitializeTimeouts();		/* establishes SIGALRM handler */
 
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, avl_sigusr2_handler);
 	pqsignal(SIGFPE, FloatExceptionHandler);
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Create a per-backend PGPROC struct in shared memory.  We must do this
@@ -1456,11 +1456,11 @@ AutoVacWorkerMain(const void *startup_data, size_t startup_data_len)
 
 	InitializeTimeouts();		/* establishes SIGALRM handler */
 
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 	pqsignal(SIGFPE, FloatExceptionHandler);
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Create a per-backend PGPROC struct in shared memory.  We must do this
diff --git a/src/backend/postmaster/bgworker.c b/src/backend/postmaster/bgworker.c
index 3914d22a514..2e4acad4f00 100644
--- a/src/backend/postmaster/bgworker.c
+++ b/src/backend/postmaster/bgworker.c
@@ -785,19 +785,19 @@ BackgroundWorkerMain(const void *startup_data, size_t startup_data_len)
 	}
 	else
 	{
-		pqsignal(SIGINT, SIG_IGN);
-		pqsignal(SIGUSR1, SIG_IGN);
-		pqsignal(SIGFPE, SIG_IGN);
+		pqsignal(SIGINT, PG_SIG_IGN);
+		pqsignal(SIGUSR1, PG_SIG_IGN);
+		pqsignal(SIGFPE, PG_SIG_IGN);
 	}
 	pqsignal(SIGTERM, die);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGHUP, SIG_IGN);
+	pqsignal(SIGHUP, PG_SIG_IGN);
 
 	InitializeTimeouts();		/* establishes SIGALRM handler */
 
-	pqsignal(SIGPIPE, SIG_IGN);
-	pqsignal(SIGUSR2, SIG_IGN);
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * If an exception is encountered, processing resumes here.
diff --git a/src/backend/postmaster/bgwriter.c b/src/backend/postmaster/bgwriter.c
index a30de4262eb..cd1bf9d919c 100644
--- a/src/backend/postmaster/bgwriter.c
+++ b/src/backend/postmaster/bgwriter.c
@@ -101,18 +101,18 @@ BackgroundWriterMain(const void *startup_data, size_t startup_data_len)
 	 * Properly accept or ignore signals that might be sent to us.
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
-	pqsignal(SIGINT, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
 	pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * We just started, assume there has been either a shutdown or
diff --git a/src/backend/postmaster/checkpointer.c b/src/backend/postmaster/checkpointer.c
index 6b424ee610f..087120db090 100644
--- a/src/backend/postmaster/checkpointer.c
+++ b/src/backend/postmaster/checkpointer.c
@@ -223,17 +223,17 @@ CheckpointerMain(const void *startup_data, size_t startup_data_len)
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
 	pqsignal(SIGINT, ReqShutdownXLOG);
-	pqsignal(SIGTERM, SIG_IGN); /* ignore SIGTERM */
+	pqsignal(SIGTERM, PG_SIG_IGN);	/* ignore SIGTERM */
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, SignalHandlerForShutdownRequest);
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Initialize so that first time-driven event happens at the correct time.
diff --git a/src/backend/postmaster/datachecksum_state.c b/src/backend/postmaster/datachecksum_state.c
index 1243949eacb..18797a8ee3d 100644
--- a/src/backend/postmaster/datachecksum_state.c
+++ b/src/backend/postmaster/datachecksum_state.c
@@ -1020,7 +1020,7 @@ DataChecksumsWorkerLauncherMain(Datum arg)
 	pqsignal(SIGTERM, die);
 	pqsignal(SIGINT, launcher_cancel_handler);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 
 	BackgroundWorkerUnblockSignals();
 
diff --git a/src/backend/postmaster/pgarch.c b/src/backend/postmaster/pgarch.c
index 0a1a1149d78..0f207ac0356 100644
--- a/src/backend/postmaster/pgarch.c
+++ b/src/backend/postmaster/pgarch.c
@@ -229,16 +229,16 @@ PgArchiverMain(const void *startup_data, size_t startup_data_len)
 	 * except for SIGHUP, SIGTERM, SIGUSR1, SIGUSR2, and SIGQUIT.
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
-	pqsignal(SIGINT, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
 	pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, pgarch_waken_stop);
 
 	/* Reset some signals that are accepted by postmaster but not here */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/* Unblock signals (they were blocked when the postmaster forked us) */
 	sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
index 6e0f41d2661..b6fd332f196 100644
--- a/src/backend/postmaster/postmaster.c
+++ b/src/backend/postmaster/postmaster.c
@@ -555,8 +555,8 @@ PostmasterMain(int argc, char *argv[])
 	pqsignal(SIGINT, handle_pm_shutdown_request_signal);
 	pqsignal(SIGQUIT, handle_pm_shutdown_request_signal);
 	pqsignal(SIGTERM, handle_pm_shutdown_request_signal);
-	pqsignal(SIGALRM, SIG_IGN); /* ignored */
-	pqsignal(SIGPIPE, SIG_IGN); /* ignored */
+	pqsignal(SIGALRM, PG_SIG_IGN);	/* ignored */
+	pqsignal(SIGPIPE, PG_SIG_IGN);	/* ignored */
 	pqsignal(SIGUSR1, handle_pm_pmsignal_signal);
 	pqsignal(SIGUSR2, dummy_handler);	/* unused, reserve for children */
 	pqsignal(SIGCHLD, handle_pm_child_exit_signal);
@@ -573,15 +573,15 @@ PostmasterMain(int argc, char *argv[])
 	 * child processes should just allow the inherited settings to stand.
 	 */
 #ifdef SIGTTIN
-	pqsignal(SIGTTIN, SIG_IGN); /* ignored */
+	pqsignal(SIGTTIN, PG_SIG_IGN);	/* ignored */
 #endif
 #ifdef SIGTTOU
-	pqsignal(SIGTTOU, SIG_IGN); /* ignored */
+	pqsignal(SIGTTOU, PG_SIG_IGN);	/* ignored */
 #endif
 
 	/* ignore SIGXFSZ, so that ulimit violations work like disk full */
 #ifdef SIGXFSZ
-	pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
+	pqsignal(SIGXFSZ, PG_SIG_IGN);	/* ignored */
 #endif
 
 	/* Begin accepting signals. */
@@ -3967,7 +3967,7 @@ process_pm_pmsignal(void)
  * Dummy signal handler
  *
  * We use this for signals that we don't actually use in the postmaster,
- * but we do use in backends.  If we were to SIG_IGN such signals in the
+ * but we do use in backends.  If we were to PG_SIG_IGN such signals in the
  * postmaster, then a newly started backend might drop a signal that arrives
  * before it's able to reconfigure its signal processing.  (See notes in
  * tcop/postgres.c.)
diff --git a/src/backend/postmaster/startup.c b/src/backend/postmaster/startup.c
index cdbe53dd262..b46bac681fe 100644
--- a/src/backend/postmaster/startup.c
+++ b/src/backend/postmaster/startup.c
@@ -226,18 +226,18 @@ StartupProcessMain(const void *startup_data, size_t startup_data_len)
 	 * Properly accept or ignore signals the postmaster might send us.
 	 */
 	pqsignal(SIGHUP, StartupProcSigHupHandler); /* reload config file */
-	pqsignal(SIGINT, SIG_IGN);	/* ignore query cancel */
+	pqsignal(SIGINT, PG_SIG_IGN);	/* ignore query cancel */
 	pqsignal(SIGTERM, StartupProcShutdownHandler);	/* request shutdown */
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
 	InitializeTimeouts();		/* establishes SIGALRM handler */
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, StartupProcTriggerHandler);
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Register timeouts needed for standby mode
diff --git a/src/backend/postmaster/syslogger.c b/src/backend/postmaster/syslogger.c
index 0c2a7bc8578..acfe0a01715 100644
--- a/src/backend/postmaster/syslogger.c
+++ b/src/backend/postmaster/syslogger.c
@@ -276,18 +276,18 @@ SysLoggerMain(const void *startup_data, size_t startup_data_len)
 
 	pqsignal(SIGHUP, SignalHandlerForConfigReload); /* set flag to read config
 													 * file */
-	pqsignal(SIGINT, SIG_IGN);
-	pqsignal(SIGTERM, SIG_IGN);
-	pqsignal(SIGQUIT, SIG_IGN);
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
+	pqsignal(SIGTERM, PG_SIG_IGN);
+	pqsignal(SIGQUIT, PG_SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, sigUsr1Handler);	/* request log rotation */
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
 
diff --git a/src/backend/postmaster/walsummarizer.c b/src/backend/postmaster/walsummarizer.c
index 20960f5b633..4f12eaf2c85 100644
--- a/src/backend/postmaster/walsummarizer.c
+++ b/src/backend/postmaster/walsummarizer.c
@@ -244,13 +244,13 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len)
 	 * Properly accept or ignore signals the postmaster might send us
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
-	pqsignal(SIGINT, SIG_IGN);	/* no query to cancel */
+	pqsignal(SIGINT, PG_SIG_IGN);	/* no query to cancel */
 	pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN); /* not used */
+	pqsignal(SIGUSR2, PG_SIG_IGN);	/* not used */
 
 	/* Advertise ourselves. */
 	on_shmem_exit(WalSummarizerShutdown, (Datum) 0);
@@ -267,7 +267,7 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len)
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * If an exception is encountered, processing resumes here.
diff --git a/src/backend/postmaster/walwriter.c b/src/backend/postmaster/walwriter.c
index 9cd86ad7022..af24d05c542 100644
--- a/src/backend/postmaster/walwriter.c
+++ b/src/backend/postmaster/walwriter.c
@@ -101,18 +101,18 @@ WalWriterMain(const void *startup_data, size_t startup_data_len)
 	 * Properly accept or ignore signals the postmaster might send us
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
-	pqsignal(SIGINT, SIG_IGN);	/* no query to cancel */
+	pqsignal(SIGINT, PG_SIG_IGN);	/* no query to cancel */
 	pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN); /* not used */
+	pqsignal(SIGUSR2, PG_SIG_IGN);	/* not used */
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Create a memory context that we will do all our work in.  We do this so
diff --git a/src/backend/replication/logical/slotsync.c b/src/backend/replication/logical/slotsync.c
index f90653e5232..354e16c9d33 100644
--- a/src/backend/replication/logical/slotsync.c
+++ b/src/backend/replication/logical/slotsync.c
@@ -1608,9 +1608,9 @@ ReplSlotSyncWorkerMain(const void *startup_data, size_t startup_data_len)
 	pqsignal(SIGTERM, die);
 	pqsignal(SIGFPE, FloatExceptionHandler);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	check_and_set_sync_info(MyProcPid);
 
diff --git a/src/backend/replication/walreceiver.c b/src/backend/replication/walreceiver.c
index 09fde92bfd7..6da5b86dbc5 100644
--- a/src/backend/replication/walreceiver.c
+++ b/src/backend/replication/walreceiver.c
@@ -248,16 +248,16 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 	/* Properly accept or ignore signals the postmaster might send us */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload); /* set flag to read config
 													 * file */
-	pqsignal(SIGINT, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
 	pqsignal(SIGTERM, die);		/* request shutdown */
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 
 	/* Reset some signals that are accepted by postmaster but not here */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/* Load the libpq-specific functions */
 	load_file("libpqwalreceiver", false);
diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c
index bad45adb004..3d4ab929f91 100644
--- a/src/backend/replication/walsender.c
+++ b/src/backend/replication/walsender.c
@@ -3897,13 +3897,13 @@ WalSndSignals(void)
 	pqsignal(SIGTERM, die);		/* request shutdown */
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
 	InitializeTimeouts();		/* establishes SIGALRM handler */
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, WalSndLastCycleHandler);	/* request a last cycle and
 												 * shutdown */
 
 	/* Reset some signals that are accepted by postmaster but not here */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 }
 
 /* Register shared-memory space needed by walsender */
diff --git a/src/backend/storage/aio/method_worker.c b/src/backend/storage/aio/method_worker.c
index a5ccd506d8c..061a93d90d4 100644
--- a/src/backend/storage/aio/method_worker.c
+++ b/src/backend/storage/aio/method_worker.c
@@ -684,10 +684,10 @@ IoWorkerMain(const void *startup_data, size_t startup_data_len)
 	 * Ignore SIGTERM, will get explicit shutdown via SIGUSR2 later in the
 	 * shutdown sequence, similar to checkpointer.
 	 */
-	pqsignal(SIGTERM, SIG_IGN);
+	pqsignal(SIGTERM, PG_SIG_IGN);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, SignalHandlerForShutdownRequest);
 
diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c
index 01f1bd6e687..a8be066afe0 100644
--- a/src/backend/storage/file/fd.c
+++ b/src/backend/storage/file/fd.c
@@ -2748,11 +2748,11 @@ OpenPipeStream(const char *command, const char *mode)
 
 TryAgain:
 	fflush(NULL);
-	pqsignal(SIGPIPE, SIG_DFL);
+	pqsignal(SIGPIPE, PG_SIG_DFL);
 	errno = 0;
 	file = popen(command, mode);
 	save_errno = errno;
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	errno = save_errno;
 	if (file != NULL)
 	{
diff --git a/src/backend/storage/ipc/waiteventset.c b/src/backend/storage/ipc/waiteventset.c
index 0f228e1e7b8..627dba0a842 100644
--- a/src/backend/storage/ipc/waiteventset.c
+++ b/src/backend/storage/ipc/waiteventset.c
@@ -348,7 +348,7 @@ InitializeWaitEventSupport(void)
 
 #ifdef WAIT_USE_KQUEUE
 	/* Ignore SIGURG, because we'll receive it via kqueue. */
-	pqsignal(SIGURG, SIG_IGN);
+	pqsignal(SIGURG, PG_SIG_IGN);
 #endif
 }
 
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index aeaf1c6db8f..9df6bc4e01b 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -3029,6 +3029,15 @@ die(SIGNAL_ARGS)
 		ProcDiePending = true;
 	}
 
+	/*
+	 * Will be 0 if unsupported by the system, but that suits us just fine.
+	 *
+	 * XXX: Seems we only should set these if not already set? We'd probably
+	 * want to know the first signal.
+	 */
+	ProcDieSenderPid = pg_siginfo->pid;
+	ProcDieSenderUid = pg_siginfo->uid;
+
 	/* for the cumulative stats system */
 	pgStatSessionEndCause = DISCONNECT_KILLED;
 
@@ -4316,17 +4325,17 @@ PostgresMain(const char *dbname, const char *username)
 		 * returns to outer loop.  This seems safer than forcing exit in the
 		 * midst of output during who-knows-what operation...
 		 */
-		pqsignal(SIGPIPE, SIG_IGN);
+		pqsignal(SIGPIPE, PG_SIG_IGN);
 		pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-		pqsignal(SIGUSR2, SIG_IGN);
+		pqsignal(SIGUSR2, PG_SIG_IGN);
 		pqsignal(SIGFPE, FloatExceptionHandler);
 
 		/*
 		 * Reset some signals that are accepted by postmaster but not by
 		 * backend
 		 */
-		pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
-									 * platforms */
+		pqsignal(SIGCHLD, PG_SIG_DFL);	/* system() requires this on some
+										 * platforms */
 	}
 
 	/* Early initialization */
diff --git a/src/fe_utils/print.c b/src/fe_utils/print.c
index 12d969e8666..f2dd52003c1 100644
--- a/src/fe_utils/print.c
+++ b/src/fe_utils/print.c
@@ -3024,7 +3024,7 @@ void
 disable_sigpipe_trap(void)
 {
 #ifndef WIN32
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 #endif
 }
 
@@ -3047,7 +3047,7 @@ void
 restore_sigpipe_trap(void)
 {
 #ifndef WIN32
-	pqsignal(SIGPIPE, always_ignore_sigpipe ? SIG_IGN : SIG_DFL);
+	pqsignal(SIGPIPE, always_ignore_sigpipe ? PG_SIG_IGN : PG_SIG_DFL);
 #endif
 }
 
diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index 509f1114ef6..44a2c7a7c7f 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -2903,10 +2903,10 @@ setup_signals(void)
 	pqsignal(SIGQUIT, trapsig);
 
 	/* Ignore SIGPIPE when writing to backend, so we can clean up */
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 
 	/* Prevent SIGSYS so we can probe for kernel calls that might not work */
-	pqsignal(SIGSYS, SIG_IGN);
+	pqsignal(SIGSYS, PG_SIG_IGN);
 #endif
 }
 
diff --git a/src/bin/pg_ctl/pg_ctl.c b/src/bin/pg_ctl/pg_ctl.c
index 3cc61455dcb..5539eb8ebef 100644
--- a/src/bin/pg_ctl/pg_ctl.c
+++ b/src/bin/pg_ctl/pg_ctl.c
@@ -868,7 +868,7 @@ trap_sigint_during_startup(SIGNAL_ARGS)
 	 * Clear the signal handler, and send the signal again, to terminate the
 	 * process as normal.
 	 */
-	pqsignal(postgres_signal_arg, SIG_DFL);
+	pqsignal(postgres_signal_arg, PG_SIG_DFL);
 	raise(postgres_signal_arg);
 }
 
diff --git a/src/bin/pg_dump/parallel.c b/src/bin/pg_dump/parallel.c
index a28561fbd84..a7bed5ecccf 100644
--- a/src/bin/pg_dump/parallel.c
+++ b/src/bin/pg_dump/parallel.c
@@ -568,9 +568,9 @@ sigTermHandler(SIGNAL_ARGS)
 	 * signal handler.  That could muck up our attempt to send PQcancel, so
 	 * disable the signals that set_cancel_handler enabled.
 	 */
-	pqsignal(SIGINT, SIG_IGN);
-	pqsignal(SIGTERM, SIG_IGN);
-	pqsignal(SIGQUIT, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
+	pqsignal(SIGTERM, PG_SIG_IGN);
+	pqsignal(SIGQUIT, PG_SIG_IGN);
 
 	/*
 	 * If we're in the leader, forward signal to all workers.  (It seems best
@@ -1049,7 +1049,7 @@ ParallelBackupStart(ArchiveHandle *AH)
 	 * the workers to inherit this setting, though.
 	 */
 #ifndef WIN32
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 #endif
 
 	/*
diff --git a/src/interfaces/libpq/legacy-pqsignal.c b/src/interfaces/libpq/legacy-pqsignal.c
index 1285b033e1b..0735e4ee0d5 100644
--- a/src/interfaces/libpq/legacy-pqsignal.c
+++ b/src/interfaces/libpq/legacy-pqsignal.c
@@ -36,10 +36,12 @@
  * is to ensure that no in-tree code accidentally calls this version.)
  */
 #undef pqsignal
-extern pqsigfunc pqsignal(int signo, pqsigfunc func);
 
-pqsigfunc
-pqsignal(int signo, pqsigfunc func)
+typedef void (*pqsigfunc_legacy) (int postgres_signal_arg);
+extern pqsigfunc_legacy pqsignal(int signo, pqsigfunc_legacy func);
+
+pqsigfunc_legacy
+pqsignal(int signo, pqsigfunc_legacy func)
 {
 #ifndef WIN32
 	struct sigaction act,
diff --git a/src/test/regress/pg_regress.c b/src/test/regress/pg_regress.c
index 0c062056982..c26efeba1ee 100644
--- a/src/test/regress/pg_regress.c
+++ b/src/test/regress/pg_regress.c
@@ -492,7 +492,7 @@ signal_remove_temp(SIGNAL_ARGS)
 {
 	remove_temp();
 
-	pqsignal(postgres_signal_arg, SIG_DFL);
+	pqsignal(postgres_signal_arg, PG_SIG_DFL);
 	raise(postgres_signal_arg);
 }
 
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index ea95e7984bc..49dfb662abc 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -4039,6 +4039,7 @@ pg_sha224_ctx
 pg_sha256_ctx
 pg_sha384_ctx
 pg_sha512_ctx
+pg_signal_info
 pg_snapshot
 pg_special_case
 pg_stack_base_t
-- 
2.53.0.1.gb2826b52eb

^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-09 03:11  Chao Li <li.evan.chao@gmail.com>
  parent: Andres Freund <andres@anarazel.de>
  1 sibling, 1 reply; 54+ messages in thread

From: Chao Li @ 2026-04-09 03:11 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Jim Jones <jim.jones@uni-muenster.de>; Andrew Dunstan <andrew@dunslane.net>; Jakub Wartak <jakub.wartak@enterprisedb.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>



> On Apr 9, 2026, at 01:01, Andres Freund <andres@anarazel.de> wrote:
> 
> Hi,
> 
> Attached is a very rough first draft for how I think this needs to look like.
> 
> Basically, SIGNAL_INFO always will pass both the signal number and extended
> information along to the signal handler. The extended information is a
> postgres specific struct. If the platform can't provide the extended
> information, the values are instead set to some default value indicating that
> the information is not known.
> 
> With that die() (and also StatementCancelHandler, ...) can just set whatever
> globals it wants, without pqsignal.c needing to know about it.
> 
> It also allows us to extend the amount of information in the future. E.g. I'd
> like to log the reason for a segfault (could e.g. be an OOM kill or an umapped
> region) to stderr.
> 
> The annoying thing about it is needing to change nearly all the existing
> references to SIG_IGN/SIG_DFL, to avoid warnings due to mismatched types.
> 
> 
> On 2026-04-08 11:13:40 +0200, Jim Jones wrote:
>> If I understood this thread correctly, the feature (v6) introduced a
>> problematic dual signature for wrapper_handler in pgsignal.c:
> 
>> +#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
>> +static void
>> +wrapper_handler(int signo, siginfo_t * info, void *context)
>> +#else
>> static void
>> wrapper_handler(SIGNAL_ARGS)
>> +#endif
> 
> I think it's not a problem for wrapper_handler to change its signature, that's
> a local implementation detail.  The problem is that the way the arguments were
> passed was just wrong.  Because signal handlers can be nested and such
> nastiness, doing any of that via global variables is a recipe for disaster.
> It's also just ugly.
> 
> 
>> .. and it should be rather done in the source (c.h) where SIGNAL_ARGS is
>> defined:
>> 
>> #ifndef SIGNAL_ARGS
>> #define SIGNAL_ARGS  int postgres_signal_arg
>> #endif
>> 
>> Something like:
>> 
>> #ifndef SIGNAL_ARGS
>> #ifdef HAVE_SA_SIGINFO
>> #define SIGNAL_ARGS  int postgres_signal_arg, siginfo_t
>> *postgres_signal_info, void *postgres_signal_context
>> #else
>> #define SIGNAL_ARGS  int postgres_signal_arg
>> #endif
>> #endif
>> 
>> But wouldn't it mean that all handlers need to be updated as well, since
>> they'd get new parameters?
> 
> All the signal handlers actually use SIGNAL_ARGS themselves, so that part is
> not a problem.
> 
> However, if we did it like you sketch above, they'd all need ifdefs etc to be
> able to access any extended information, which seems like a terrible
> idea. Especially if we want this information on multiple platforms, where the
> struct to be passed would differ.
> 
> Hence in my prototype it's hidden behind a platform indepenedent struct of our
> own.
> 
> 
>> If this is the case, the change can be quite substantial.
> 
> It's a bit annoying to do all the s/\b(SIG_(IGN|DFL)/PG_$1/, but it's not that
> bad, I think?
> 
> I unfortunately don't see a good other way to deal with it.  We could have a
> macro wrapper around pqsignal() that checks for SIG_IGN with a cast to the
> system type, but that seems exceedingly ugly.
> 
> Greetings,
> 
> Andres Freund
> <v1-0001-WIP-Support-for-extended-information-about-signal.patch>

I think the core idea here is to add a new parameter so signal handlers can receive “pg_signal_info". Compared to my earlier proposal, which stored sender info in file-scope variables, I agree this solution is more flexible. I think my earlier direction was mainly trying to avoid changing the signal handler interface.

So I have no objection to the overall direction. Since the patch is marked as WIP, I didn't review all the details yet. But one thing I want to point out is:
```
+typedef struct pg_signal_info
+{
+	pid_t		pid;			/* pid of sending process or 0 if unknown */
+	uid_t		uid;			/* uid of sending process or 0 if unknown */
+} pg_signal_info;
```

For uid, 0 is usually a valid value for root. So using 0 as the “unknown” value seems a bit awkward. Maybe we should instead document something like "uid is only meaningful when pid is not 0".

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/









^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-09 06:14  Chao Li <li.evan.chao@gmail.com>
  parent: Chao Li <li.evan.chao@gmail.com>
  0 siblings, 1 reply; 54+ messages in thread

From: Chao Li @ 2026-04-09 06:14 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Jim Jones <jim.jones@uni-muenster.de>; Andrew Dunstan <andrew@dunslane.net>; Jakub Wartak <jakub.wartak@enterprisedb.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>



> On Apr 9, 2026, at 11:11, Chao Li <li.evan.chao@gmail.com> wrote:
> 
> 
> 
>> On Apr 9, 2026, at 01:01, Andres Freund <andres@anarazel.de> wrote:
>> 
>> Hi,
>> 
>> Attached is a very rough first draft for how I think this needs to look like.
>> 
>> Basically, SIGNAL_INFO always will pass both the signal number and extended
>> information along to the signal handler. The extended information is a
>> postgres specific struct. If the platform can't provide the extended
>> information, the values are instead set to some default value indicating that
>> the information is not known.
>> 
>> With that die() (and also StatementCancelHandler, ...) can just set whatever
>> globals it wants, without pqsignal.c needing to know about it.
>> 
>> It also allows us to extend the amount of information in the future. E.g. I'd
>> like to log the reason for a segfault (could e.g. be an OOM kill or an umapped
>> region) to stderr.
>> 
>> The annoying thing about it is needing to change nearly all the existing
>> references to SIG_IGN/SIG_DFL, to avoid warnings due to mismatched types.
>> 
>> 
>> On 2026-04-08 11:13:40 +0200, Jim Jones wrote:
>>> If I understood this thread correctly, the feature (v6) introduced a
>>> problematic dual signature for wrapper_handler in pgsignal.c:
>> 
>>> +#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
>>> +static void
>>> +wrapper_handler(int signo, siginfo_t * info, void *context)
>>> +#else
>>> static void
>>> wrapper_handler(SIGNAL_ARGS)
>>> +#endif
>> 
>> I think it's not a problem for wrapper_handler to change its signature, that's
>> a local implementation detail.  The problem is that the way the arguments were
>> passed was just wrong.  Because signal handlers can be nested and such
>> nastiness, doing any of that via global variables is a recipe for disaster.
>> It's also just ugly.
>> 
>> 
>>> .. and it should be rather done in the source (c.h) where SIGNAL_ARGS is
>>> defined:
>>> 
>>> #ifndef SIGNAL_ARGS
>>> #define SIGNAL_ARGS  int postgres_signal_arg
>>> #endif
>>> 
>>> Something like:
>>> 
>>> #ifndef SIGNAL_ARGS
>>> #ifdef HAVE_SA_SIGINFO
>>> #define SIGNAL_ARGS  int postgres_signal_arg, siginfo_t
>>> *postgres_signal_info, void *postgres_signal_context
>>> #else
>>> #define SIGNAL_ARGS  int postgres_signal_arg
>>> #endif
>>> #endif
>>> 
>>> But wouldn't it mean that all handlers need to be updated as well, since
>>> they'd get new parameters?
>> 
>> All the signal handlers actually use SIGNAL_ARGS themselves, so that part is
>> not a problem.
>> 
>> However, if we did it like you sketch above, they'd all need ifdefs etc to be
>> able to access any extended information, which seems like a terrible
>> idea. Especially if we want this information on multiple platforms, where the
>> struct to be passed would differ.
>> 
>> Hence in my prototype it's hidden behind a platform indepenedent struct of our
>> own.
>> 
>> 
>>> If this is the case, the change can be quite substantial.
>> 
>> It's a bit annoying to do all the s/\b(SIG_(IGN|DFL)/PG_$1/, but it's not that
>> bad, I think?
>> 
>> I unfortunately don't see a good other way to deal with it.  We could have a
>> macro wrapper around pqsignal() that checks for SIG_IGN with a cast to the
>> system type, but that seems exceedingly ugly.
>> 
>> Greetings,
>> 
>> Andres Freund
>> <v1-0001-WIP-Support-for-extended-information-about-signal.patch>
> 
> I think the core idea here is to add a new parameter so signal handlers can receive “pg_signal_info". Compared to my earlier proposal, which stored sender info in file-scope variables, I agree this solution is more flexible. I think my earlier direction was mainly trying to avoid changing the signal handler interface.
> 
> So I have no objection to the overall direction. Since the patch is marked as WIP, I didn't review all the details yet. But one thing I want to point out is:
> ```
> +typedef struct pg_signal_info
> +{
> + pid_t pid; /* pid of sending process or 0 if unknown */
> + uid_t uid; /* uid of sending process or 0 if unknown */
> +} pg_signal_info;
> ```
> 
> For uid, 0 is usually a valid value for root. So using 0 as the “unknown” value seems a bit awkward. Maybe we should instead document something like "uid is only meaningful when pid is not 0".
> 

Forgot to mention, I got a lot of compile warnings, for example:
```
parallel.c:1052:20: warning: cast from 'void (*)(int)' to 'pqsigfunc' (aka 'void (*)(int, struct pg_signal_info *)') converts to incompatible function type [-Wcast-function-type-mismatch]
 1052 |         pqsignal(SIGPIPE, PG_SIG_IGN);
      |                           ^~~~~~~~~~
../../../src/include/port.h:551:20: note: expanded from macro 'PG_SIG_IGN'
  551 | #define PG_SIG_IGN (pqsigfunc) SIG_IGN
      |                    ^~~~~~~~~~~~~~~~~~~
4 warnings generated.
```

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/









^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-09 10:59  Andrew Dunstan <andrew@dunslane.net>
  parent: Andres Freund <andres@anarazel.de>
  1 sibling, 2 replies; 54+ messages in thread

From: Andrew Dunstan @ 2026-04-09 10:59 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; +Cc: Chao Li <li.evan.chao@gmail.com>; Jakub Wartak <jakub.wartak@enterprisedb.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>


On 2026-04-08 We 1:01 PM, Andres Freund wrote:
> Hi,
>
> Attached is a very rough first draft for how I think this needs to look like.
>
> Basically, SIGNAL_INFO always will pass both the signal number and extended
> information along to the signal handler. The extended information is a
> postgres specific struct. If the platform can't provide the extended
> information, the values are instead set to some default value indicating that
> the information is not known.
>
> With that die() (and also StatementCancelHandler, ...) can just set whatever
> globals it wants, without pqsignal.c needing to know about it.
>
> It also allows us to extend the amount of information in the future. E.g. I'd
> like to log the reason for a segfault (could e.g. be an OOM kill or an umapped
> region) to stderr.
>
> The annoying thing about it is needing to change nearly all the existing
> references to SIG_IGN/SIG_DFL, to avoid warnings due to mismatched types.


I agree that's annoying. The only way around it I found was via some 
casting to/from void* that I suspect you would find a cure worse than 
the disease.

I reworked your patch slightly. This version fixes the translatability 
issue you raised earlier, makes the TAP test from the original commit 
more robust, and  tries to resolve your XXX issue by moving the 
assignment of ProcDieSenderPid/Uid inside the "if 
(!proc_exit_inprogress)" block.


cheers


andrew



--
Andrew Dunstan
EDB:https://www.enterprisedb.com

Attachments:

  [text/x-patch] 0001-Rework-signal-sender-errdetail-to-pass-info-via-hand.patch (34.3K, ../../acd7c8a3-9646-4023-8938-d49eb9c6a3f1@dunslane.net/3-0001-Rework-signal-sender-errdetail-to-pass-info-via-hand.patch)
  download | inline diff:
From c3078bfb08f22cddbaa17cc4558c1e7daa8b0eca Mon Sep 17 00:00:00 2001
From: Andrew Dunstan <andrew@dunslane.net>
Date: Wed, 8 Apr 2026 16:09:35 -0400
Subject: [PATCH] Rework signal-sender errdetail to pass info via handler
 arguments.

Commit 095c9d4cf06 added errdetail() reporting of the PID and UID of
the process that sent a termination signal.  However, as noted by
Andres Freund, the implementation had architectural problems:

1. wrapper_handler() in pqsignal.c contained SIGTERM-specific logic
   (setting ProcDieSenderPid/Uid), violating its role as a generic
   signal dispatch wrapper.

2. Using globals to pass sender info between wrapper_handler and the
   real handler is unsafe when signals nest on some platforms.

3. The syncrep.c errdetail used psprintf() to conditionally embed
   text via %s, breaking translatability.

Adopt the approach proposed by Andres Freund: introduce a
pg_signal_info struct that is passed as an argument to all signal
handlers via the SIGNAL_ARGS macro.  wrapper_handler populates it
from siginfo_t when SA_SIGINFO is available, or with zeros otherwise.
This keeps wrapper_handler fully generic and avoids any globals for
passing signal metadata.

Since pqsigfunc now has a different signature from the system's
signal handler type, SIG_IGN and SIG_DFL can no longer be passed
directly to pqsignal().  Introduce PG_SIG_IGN and PG_SIG_DFL macros
that cast to the new pqsigfunc type, and update all call sites.
The legacy pqsignal() in libpq retains its original signature via
a local typedef.

Only die() reads pg_siginfo today, copying the sender PID/UID into
ProcDieSenderPid/Uid for later use by ProcessInterrupts().  Only the
first SIGTERM's sender info is recorded.

Also fix the syncrep.c translatability issue by using separate ereport
calls with complete, independently translatable errdetail strings.

Also make the psql TAP test require the DETAIL line on platforms with
SA_SIGINFO, rather than making it unconditionally optional.

Author: Andres Freund <andres@anarazel.de>
Reviewed-by: Andrew Dunstan <andrew@dunslane.net>
Discussion: https://postgr.es/m/cwyyryh2veejuxbj5ifzyaejw7jhhqc5mrdeq56xckknsdecn2@6hzfcxde2nm5
Discussion: https://postgr.es/m/jygesyr7mwg7ovdbxpmjvvbi3hccptpkcreqb645h7f56puwbz@hmkkwi3melfe
---
 src/backend/bootstrap/bootstrap.c           |  8 +--
 src/backend/postmaster/autovacuum.c         | 10 +--
 src/backend/postmaster/bgworker.c           | 14 ++--
 src/backend/postmaster/bgwriter.c           | 10 +--
 src/backend/postmaster/checkpointer.c       |  8 +--
 src/backend/postmaster/datachecksum_state.c |  2 +-
 src/backend/postmaster/pgarch.c             |  8 +--
 src/backend/postmaster/postmaster.c         | 12 ++--
 src/backend/postmaster/startup.c            |  6 +-
 src/backend/postmaster/syslogger.c          | 14 ++--
 src/backend/postmaster/walsummarizer.c      | 10 +--
 src/backend/postmaster/walwriter.c          | 10 +--
 src/backend/replication/logical/slotsync.c  |  6 +-
 src/backend/replication/syncrep.c           | 28 ++++----
 src/backend/replication/walreceiver.c       | 10 +--
 src/backend/replication/walsender.c         |  4 +-
 src/backend/storage/aio/method_worker.c     |  6 +-
 src/backend/storage/file/fd.c               |  4 +-
 src/backend/storage/ipc/waiteventset.c      |  2 +-
 src/backend/tcop/postgres.c                 | 19 ++++--
 src/bin/initdb/initdb.c                     |  4 +-
 src/bin/pg_ctl/pg_ctl.c                     |  2 +-
 src/bin/pg_dump/parallel.c                  |  8 +--
 src/bin/psql/t/001_basic.pl                 |  5 +-
 src/fe_utils/print.c                        |  4 +-
 src/include/c.h                             | 27 +++++---
 src/include/port.h                          |  3 +
 src/interfaces/libpq/legacy-pqsignal.c      |  8 ++-
 src/port/pqsignal.c                         | 75 ++++++++++++++-------
 src/test/regress/pg_regress.c               |  2 +-
 src/tools/pgindent/typedefs.list            |  1 +
 31 files changed, 191 insertions(+), 139 deletions(-)

diff --git a/src/backend/bootstrap/bootstrap.c b/src/backend/bootstrap/bootstrap.c
index 63378ab3d8c..b487289d4a3 100644
--- a/src/backend/bootstrap/bootstrap.c
+++ b/src/backend/bootstrap/bootstrap.c
@@ -463,10 +463,10 @@ bootstrap_signals(void)
 	 * mode; "curl up and die" is a sufficient response for all these cases.
 	 * Let's set that handling explicitly, as documentation if nothing else.
 	 */
-	pqsignal(SIGHUP, SIG_DFL);
-	pqsignal(SIGINT, SIG_DFL);
-	pqsignal(SIGTERM, SIG_DFL);
-	pqsignal(SIGQUIT, SIG_DFL);
+	pqsignal(SIGHUP, PG_SIG_DFL);
+	pqsignal(SIGINT, PG_SIG_DFL);
+	pqsignal(SIGTERM, PG_SIG_DFL);
+	pqsignal(SIGQUIT, PG_SIG_DFL);
 }
 
 /* ----------------------------------------------------------------
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index c4d6b8811bf..9fedf68c6af 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -448,11 +448,11 @@ AutoVacLauncherMain(const void *startup_data, size_t startup_data_len)
 
 	InitializeTimeouts();		/* establishes SIGALRM handler */
 
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, avl_sigusr2_handler);
 	pqsignal(SIGFPE, FloatExceptionHandler);
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Create a per-backend PGPROC struct in shared memory.  We must do this
@@ -1459,11 +1459,11 @@ AutoVacWorkerMain(const void *startup_data, size_t startup_data_len)
 
 	InitializeTimeouts();		/* establishes SIGALRM handler */
 
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 	pqsignal(SIGFPE, FloatExceptionHandler);
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Create a per-backend PGPROC struct in shared memory.  We must do this
diff --git a/src/backend/postmaster/bgworker.c b/src/backend/postmaster/bgworker.c
index 0992b9b6353..4569d9d232f 100644
--- a/src/backend/postmaster/bgworker.c
+++ b/src/backend/postmaster/bgworker.c
@@ -780,19 +780,19 @@ BackgroundWorkerMain(const void *startup_data, size_t startup_data_len)
 	}
 	else
 	{
-		pqsignal(SIGINT, SIG_IGN);
-		pqsignal(SIGUSR1, SIG_IGN);
-		pqsignal(SIGFPE, SIG_IGN);
+		pqsignal(SIGINT, PG_SIG_IGN);
+		pqsignal(SIGUSR1, PG_SIG_IGN);
+		pqsignal(SIGFPE, PG_SIG_IGN);
 	}
 	pqsignal(SIGTERM, die);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGHUP, SIG_IGN);
+	pqsignal(SIGHUP, PG_SIG_IGN);
 
 	InitializeTimeouts();		/* establishes SIGALRM handler */
 
-	pqsignal(SIGPIPE, SIG_IGN);
-	pqsignal(SIGUSR2, SIG_IGN);
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * If an exception is encountered, processing resumes here.
diff --git a/src/backend/postmaster/bgwriter.c b/src/backend/postmaster/bgwriter.c
index 1d8947774a9..d364382303a 100644
--- a/src/backend/postmaster/bgwriter.c
+++ b/src/backend/postmaster/bgwriter.c
@@ -101,18 +101,18 @@ BackgroundWriterMain(const void *startup_data, size_t startup_data_len)
 	 * Properly accept or ignore signals that might be sent to us.
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
-	pqsignal(SIGINT, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
 	pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * We just started, assume there has been either a shutdown or
diff --git a/src/backend/postmaster/checkpointer.c b/src/backend/postmaster/checkpointer.c
index 6b424ee610f..087120db090 100644
--- a/src/backend/postmaster/checkpointer.c
+++ b/src/backend/postmaster/checkpointer.c
@@ -223,17 +223,17 @@ CheckpointerMain(const void *startup_data, size_t startup_data_len)
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
 	pqsignal(SIGINT, ReqShutdownXLOG);
-	pqsignal(SIGTERM, SIG_IGN); /* ignore SIGTERM */
+	pqsignal(SIGTERM, PG_SIG_IGN);	/* ignore SIGTERM */
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, SignalHandlerForShutdownRequest);
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Initialize so that first time-driven event happens at the correct time.
diff --git a/src/backend/postmaster/datachecksum_state.c b/src/backend/postmaster/datachecksum_state.c
index 1243949eacb..18797a8ee3d 100644
--- a/src/backend/postmaster/datachecksum_state.c
+++ b/src/backend/postmaster/datachecksum_state.c
@@ -1020,7 +1020,7 @@ DataChecksumsWorkerLauncherMain(Datum arg)
 	pqsignal(SIGTERM, die);
 	pqsignal(SIGINT, launcher_cancel_handler);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 
 	BackgroundWorkerUnblockSignals();
 
diff --git a/src/backend/postmaster/pgarch.c b/src/backend/postmaster/pgarch.c
index 0a1a1149d78..0f207ac0356 100644
--- a/src/backend/postmaster/pgarch.c
+++ b/src/backend/postmaster/pgarch.c
@@ -229,16 +229,16 @@ PgArchiverMain(const void *startup_data, size_t startup_data_len)
 	 * except for SIGHUP, SIGTERM, SIGUSR1, SIGUSR2, and SIGQUIT.
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
-	pqsignal(SIGINT, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
 	pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, pgarch_waken_stop);
 
 	/* Reset some signals that are accepted by postmaster but not here */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/* Unblock signals (they were blocked when the postmaster forked us) */
 	sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
index 6f13e8f40a0..0a9b336d650 100644
--- a/src/backend/postmaster/postmaster.c
+++ b/src/backend/postmaster/postmaster.c
@@ -553,8 +553,8 @@ PostmasterMain(int argc, char *argv[])
 	pqsignal(SIGINT, handle_pm_shutdown_request_signal);
 	pqsignal(SIGQUIT, handle_pm_shutdown_request_signal);
 	pqsignal(SIGTERM, handle_pm_shutdown_request_signal);
-	pqsignal(SIGALRM, SIG_IGN); /* ignored */
-	pqsignal(SIGPIPE, SIG_IGN); /* ignored */
+	pqsignal(SIGALRM, PG_SIG_IGN);	/* ignored */
+	pqsignal(SIGPIPE, PG_SIG_IGN);	/* ignored */
 	pqsignal(SIGUSR1, handle_pm_pmsignal_signal);
 	pqsignal(SIGUSR2, dummy_handler);	/* unused, reserve for children */
 	pqsignal(SIGCHLD, handle_pm_child_exit_signal);
@@ -571,15 +571,15 @@ PostmasterMain(int argc, char *argv[])
 	 * child processes should just allow the inherited settings to stand.
 	 */
 #ifdef SIGTTIN
-	pqsignal(SIGTTIN, SIG_IGN); /* ignored */
+	pqsignal(SIGTTIN, PG_SIG_IGN);	/* ignored */
 #endif
 #ifdef SIGTTOU
-	pqsignal(SIGTTOU, SIG_IGN); /* ignored */
+	pqsignal(SIGTTOU, PG_SIG_IGN);	/* ignored */
 #endif
 
 	/* ignore SIGXFSZ, so that ulimit violations work like disk full */
 #ifdef SIGXFSZ
-	pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
+	pqsignal(SIGXFSZ, PG_SIG_IGN);	/* ignored */
 #endif
 
 	/* Begin accepting signals. */
@@ -3939,7 +3939,7 @@ process_pm_pmsignal(void)
  * Dummy signal handler
  *
  * We use this for signals that we don't actually use in the postmaster,
- * but we do use in backends.  If we were to SIG_IGN such signals in the
+ * but we do use in backends.  If we were to PG_SIG_IGN such signals in the
  * postmaster, then a newly started backend might drop a signal that arrives
  * before it's able to reconfigure its signal processing.  (See notes in
  * tcop/postgres.c.)
diff --git a/src/backend/postmaster/startup.c b/src/backend/postmaster/startup.c
index cdbe53dd262..b46bac681fe 100644
--- a/src/backend/postmaster/startup.c
+++ b/src/backend/postmaster/startup.c
@@ -226,18 +226,18 @@ StartupProcessMain(const void *startup_data, size_t startup_data_len)
 	 * Properly accept or ignore signals the postmaster might send us.
 	 */
 	pqsignal(SIGHUP, StartupProcSigHupHandler); /* reload config file */
-	pqsignal(SIGINT, SIG_IGN);	/* ignore query cancel */
+	pqsignal(SIGINT, PG_SIG_IGN);	/* ignore query cancel */
 	pqsignal(SIGTERM, StartupProcShutdownHandler);	/* request shutdown */
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
 	InitializeTimeouts();		/* establishes SIGALRM handler */
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, StartupProcTriggerHandler);
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Register timeouts needed for standby mode
diff --git a/src/backend/postmaster/syslogger.c b/src/backend/postmaster/syslogger.c
index 0c2a7bc8578..acfe0a01715 100644
--- a/src/backend/postmaster/syslogger.c
+++ b/src/backend/postmaster/syslogger.c
@@ -276,18 +276,18 @@ SysLoggerMain(const void *startup_data, size_t startup_data_len)
 
 	pqsignal(SIGHUP, SignalHandlerForConfigReload); /* set flag to read config
 													 * file */
-	pqsignal(SIGINT, SIG_IGN);
-	pqsignal(SIGTERM, SIG_IGN);
-	pqsignal(SIGQUIT, SIG_IGN);
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
+	pqsignal(SIGTERM, PG_SIG_IGN);
+	pqsignal(SIGQUIT, PG_SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, sigUsr1Handler);	/* request log rotation */
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
 
diff --git a/src/backend/postmaster/walsummarizer.c b/src/backend/postmaster/walsummarizer.c
index 20960f5b633..4f12eaf2c85 100644
--- a/src/backend/postmaster/walsummarizer.c
+++ b/src/backend/postmaster/walsummarizer.c
@@ -244,13 +244,13 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len)
 	 * Properly accept or ignore signals the postmaster might send us
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
-	pqsignal(SIGINT, SIG_IGN);	/* no query to cancel */
+	pqsignal(SIGINT, PG_SIG_IGN);	/* no query to cancel */
 	pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN); /* not used */
+	pqsignal(SIGUSR2, PG_SIG_IGN);	/* not used */
 
 	/* Advertise ourselves. */
 	on_shmem_exit(WalSummarizerShutdown, (Datum) 0);
@@ -267,7 +267,7 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len)
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * If an exception is encountered, processing resumes here.
diff --git a/src/backend/postmaster/walwriter.c b/src/backend/postmaster/walwriter.c
index 9cd86ad7022..af24d05c542 100644
--- a/src/backend/postmaster/walwriter.c
+++ b/src/backend/postmaster/walwriter.c
@@ -101,18 +101,18 @@ WalWriterMain(const void *startup_data, size_t startup_data_len)
 	 * Properly accept or ignore signals the postmaster might send us
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
-	pqsignal(SIGINT, SIG_IGN);	/* no query to cancel */
+	pqsignal(SIGINT, PG_SIG_IGN);	/* no query to cancel */
 	pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN); /* not used */
+	pqsignal(SIGUSR2, PG_SIG_IGN);	/* not used */
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Create a memory context that we will do all our work in.  We do this so
diff --git a/src/backend/replication/logical/slotsync.c b/src/backend/replication/logical/slotsync.c
index 8b53bd3ac7f..01607244bff 100644
--- a/src/backend/replication/logical/slotsync.c
+++ b/src/backend/replication/logical/slotsync.c
@@ -1555,9 +1555,9 @@ ReplSlotSyncWorkerMain(const void *startup_data, size_t startup_data_len)
 	pqsignal(SIGTERM, die);
 	pqsignal(SIGFPE, FloatExceptionHandler);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	check_and_set_sync_info(MyProcPid);
 
diff --git a/src/backend/replication/syncrep.c b/src/backend/replication/syncrep.c
index 46a778f0917..896ba45412d 100644
--- a/src/backend/replication/syncrep.c
+++ b/src/backend/replication/syncrep.c
@@ -300,22 +300,18 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 		 */
 		if (ProcDiePending)
 		{
-			/*
-			 * ProcDieSenderPid/Uid are read directly from the globals here
-			 * rather than copied to locals first; a second SIGTERM could
-			 * change them between reads, but that is harmless because the
-			 * process is about to die anyway.  The signal sender detail is
-			 * inlined rather than using a separate errdetail() call because
-			 * it must be appended to the existing detail message.
-			 */
-			ereport(WARNING,
-					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.%s",
-							   ProcDieSenderPid == 0 ? "" :
-							   psprintf("\nSignal sent by PID %d, UID %d.",
-										(int) ProcDieSenderPid,
-										(int) ProcDieSenderUid))));
+			if (ProcDieSenderPid != 0)
+				ereport(WARNING,
+						(errcode(ERRCODE_ADMIN_SHUTDOWN),
+						 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
+						 errdetail("The transaction has already committed locally, but might not have been replicated to the standby. Signal sent by PID %d, UID %d.",
+								   (int) ProcDieSenderPid,
+								   (int) ProcDieSenderUid)));
+			else
+				ereport(WARNING,
+						(errcode(ERRCODE_ADMIN_SHUTDOWN),
+						 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
+						 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
 			whereToSendOutput = DestNone;
 			SyncRepCancelWait();
 			break;
diff --git a/src/backend/replication/walreceiver.c b/src/backend/replication/walreceiver.c
index a437273cf9a..9ad8b6648e6 100644
--- a/src/backend/replication/walreceiver.c
+++ b/src/backend/replication/walreceiver.c
@@ -250,16 +250,16 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 	/* Properly accept or ignore signals the postmaster might send us */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload); /* set flag to read config
 													 * file */
-	pqsignal(SIGINT, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
 	pqsignal(SIGTERM, die);		/* request shutdown */
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 
 	/* Reset some signals that are accepted by postmaster but not here */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/* Load the libpq-specific functions */
 	load_file("libpqwalreceiver", false);
diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c
index b4a2117a7f9..3957213a057 100644
--- a/src/backend/replication/walsender.c
+++ b/src/backend/replication/walsender.c
@@ -3896,13 +3896,13 @@ WalSndSignals(void)
 	pqsignal(SIGTERM, die);		/* request shutdown */
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
 	InitializeTimeouts();		/* establishes SIGALRM handler */
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, WalSndLastCycleHandler);	/* request a last cycle and
 												 * shutdown */
 
 	/* Reset some signals that are accepted by postmaster but not here */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 }
 
 /* Register shared-memory space needed by walsender */
diff --git a/src/backend/storage/aio/method_worker.c b/src/backend/storage/aio/method_worker.c
index eb686cede1a..ca24af126e7 100644
--- a/src/backend/storage/aio/method_worker.c
+++ b/src/backend/storage/aio/method_worker.c
@@ -382,10 +382,10 @@ IoWorkerMain(const void *startup_data, size_t startup_data_len)
 	 * Ignore SIGTERM, will get explicit shutdown via SIGUSR2 later in the
 	 * shutdown sequence, similar to checkpointer.
 	 */
-	pqsignal(SIGTERM, SIG_IGN);
+	pqsignal(SIGTERM, PG_SIG_IGN);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, SignalHandlerForShutdownRequest);
 
diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c
index 01f1bd6e687..a8be066afe0 100644
--- a/src/backend/storage/file/fd.c
+++ b/src/backend/storage/file/fd.c
@@ -2748,11 +2748,11 @@ OpenPipeStream(const char *command, const char *mode)
 
 TryAgain:
 	fflush(NULL);
-	pqsignal(SIGPIPE, SIG_DFL);
+	pqsignal(SIGPIPE, PG_SIG_DFL);
 	errno = 0;
 	file = popen(command, mode);
 	save_errno = errno;
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	errno = save_errno;
 	if (file != NULL)
 	{
diff --git a/src/backend/storage/ipc/waiteventset.c b/src/backend/storage/ipc/waiteventset.c
index 0f228e1e7b8..627dba0a842 100644
--- a/src/backend/storage/ipc/waiteventset.c
+++ b/src/backend/storage/ipc/waiteventset.c
@@ -348,7 +348,7 @@ InitializeWaitEventSupport(void)
 
 #ifdef WAIT_USE_KQUEUE
 	/* Ignore SIGURG, because we'll receive it via kqueue. */
-	pqsignal(SIGURG, SIG_IGN);
+	pqsignal(SIGURG, PG_SIG_IGN);
 #endif
 }
 
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 4fb18741dc5..14df4d9aaf8 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -3025,6 +3025,17 @@ die(SIGNAL_ARGS)
 	{
 		InterruptPending = true;
 		ProcDiePending = true;
+
+		/*
+		 * Record who sent the signal.  Will be 0 on platforms without
+		 * SA_SIGINFO, which is fine -- ProcessInterrupts() checks for that.
+		 * Only set on the first SIGTERM so we report the original sender.
+		 */
+		if (ProcDieSenderPid == 0)
+		{
+			ProcDieSenderPid = pg_siginfo->pid;
+			ProcDieSenderUid = pg_siginfo->uid;
+		}
 	}
 
 	/* for the cumulative stats system */
@@ -4308,17 +4319,17 @@ PostgresMain(const char *dbname, const char *username)
 		 * returns to outer loop.  This seems safer than forcing exit in the
 		 * midst of output during who-knows-what operation...
 		 */
-		pqsignal(SIGPIPE, SIG_IGN);
+		pqsignal(SIGPIPE, PG_SIG_IGN);
 		pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-		pqsignal(SIGUSR2, SIG_IGN);
+		pqsignal(SIGUSR2, PG_SIG_IGN);
 		pqsignal(SIGFPE, FloatExceptionHandler);
 
 		/*
 		 * Reset some signals that are accepted by postmaster but not by
 		 * backend
 		 */
-		pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
-									 * platforms */
+		pqsignal(SIGCHLD, PG_SIG_DFL);	/* system() requires this on some
+										 * platforms */
 	}
 
 	/* Early initialization */
diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index 509f1114ef6..44a2c7a7c7f 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -2903,10 +2903,10 @@ setup_signals(void)
 	pqsignal(SIGQUIT, trapsig);
 
 	/* Ignore SIGPIPE when writing to backend, so we can clean up */
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 
 	/* Prevent SIGSYS so we can probe for kernel calls that might not work */
-	pqsignal(SIGSYS, SIG_IGN);
+	pqsignal(SIGSYS, PG_SIG_IGN);
 #endif
 }
 
diff --git a/src/bin/pg_ctl/pg_ctl.c b/src/bin/pg_ctl/pg_ctl.c
index 3cc61455dcb..5539eb8ebef 100644
--- a/src/bin/pg_ctl/pg_ctl.c
+++ b/src/bin/pg_ctl/pg_ctl.c
@@ -868,7 +868,7 @@ trap_sigint_during_startup(SIGNAL_ARGS)
 	 * Clear the signal handler, and send the signal again, to terminate the
 	 * process as normal.
 	 */
-	pqsignal(postgres_signal_arg, SIG_DFL);
+	pqsignal(postgres_signal_arg, PG_SIG_DFL);
 	raise(postgres_signal_arg);
 }
 
diff --git a/src/bin/pg_dump/parallel.c b/src/bin/pg_dump/parallel.c
index a28561fbd84..a7bed5ecccf 100644
--- a/src/bin/pg_dump/parallel.c
+++ b/src/bin/pg_dump/parallel.c
@@ -568,9 +568,9 @@ sigTermHandler(SIGNAL_ARGS)
 	 * signal handler.  That could muck up our attempt to send PQcancel, so
 	 * disable the signals that set_cancel_handler enabled.
 	 */
-	pqsignal(SIGINT, SIG_IGN);
-	pqsignal(SIGTERM, SIG_IGN);
-	pqsignal(SIGQUIT, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
+	pqsignal(SIGTERM, PG_SIG_IGN);
+	pqsignal(SIGQUIT, PG_SIG_IGN);
 
 	/*
 	 * If we're in the leader, forward signal to all workers.  (It seems best
@@ -1049,7 +1049,7 @@ ParallelBackupStart(ArchiveHandle *AH)
 	 * the workers to inherit this setting, though.
 	 */
 #ifndef WIN32
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 #endif
 
 	/*
diff --git a/src/bin/psql/t/001_basic.pl b/src/bin/psql/t/001_basic.pl
index 7c21204c1f2..9d966c7bece 100644
--- a/src/bin/psql/t/001_basic.pl
+++ b/src/bin/psql/t/001_basic.pl
@@ -142,8 +142,11 @@ my ($ret, $out, $err) = $node->psql('postgres',
 is($ret, 2, 'server crash: psql exit code');
 like($out, qr/before/, 'server crash: output before crash');
 unlike($out, qr/AFTER/, 'server crash: no output after crash');
+my $detail_re = check_pg_config("#define HAVE_SA_SIGINFO 1")
+	? qr/DETAIL:  Signal sent by PID \d+, UID \d+\.\n/
+	: qr//;
 like( $err, qr/psql:<stdin>:2: FATAL:  terminating connection due to administrator command
-(?:DETAIL:  Signal sent by PID \d+, UID \d+\.\n)?psql:<stdin>:2: server closed the connection unexpectedly
+${detail_re}psql:<stdin>:2: server closed the connection unexpectedly
 	This probably means the server terminated abnormally
 	before or while processing the request.
 psql:<stdin>:2: error: connection to server was lost/,
diff --git a/src/fe_utils/print.c b/src/fe_utils/print.c
index 12d969e8666..f2dd52003c1 100644
--- a/src/fe_utils/print.c
+++ b/src/fe_utils/print.c
@@ -3024,7 +3024,7 @@ void
 disable_sigpipe_trap(void)
 {
 #ifndef WIN32
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 #endif
 }
 
@@ -3047,7 +3047,7 @@ void
 restore_sigpipe_trap(void)
 {
 #ifndef WIN32
-	pqsignal(SIGPIPE, always_ignore_sigpipe ? SIG_IGN : SIG_DFL);
+	pqsignal(SIGPIPE, always_ignore_sigpipe ? PG_SIG_IGN : PG_SIG_DFL);
 #endif
 }
 
diff --git a/src/include/c.h b/src/include/c.h
index 88d13ec9993..77ea73cc707 100644
--- a/src/include/c.h
+++ b/src/include/c.h
@@ -1441,17 +1441,26 @@ extern int	fdatasync(int fd);
 #endif
 
 /*
- * The following is used as the arg list for signal handlers.  Any ports
- * that take something other than an int argument should override this in
- * their pg_config_os.h file.  Note that variable names are required
- * because it is used in both the prototypes as well as the definitions.
- * Note also the long name.  We expect that this won't collide with
- * other names causing compiler warnings.
+ * Platform independent struct representing additional information about the
+ * received signal.  If the system does not support the extended information,
+ * or a field does not apply to the signal, the value is instead reset to the
+ * documented default value.
  */
+typedef struct pg_signal_info
+{
+	pid_t		pid;			/* pid of sending process or 0 if unknown */
+	uid_t		uid;			/* uid of sending process or 0 if unknown */
+} pg_signal_info;
 
-#ifndef SIGNAL_ARGS
-#define SIGNAL_ARGS  int postgres_signal_arg
-#endif
+/*
+ * The following is used as the arg list for signal handlers. These days we
+ * use the same argument to all signal handlers and hide the difference
+ * between platforms in wrapper functions.
+ *
+ * SIGNAL_ARGS just exists separately from the pqsignal() definition for
+ * historical reasons.
+ */
+#define SIGNAL_ARGS  int postgres_signal_arg, pg_signal_info *pg_siginfo
 
 /*
  * When there is no sigsetjmp, its functionality is provided by plain
diff --git a/src/include/port.h b/src/include/port.h
index 51df9b80e7d..7db476d7b01 100644
--- a/src/include/port.h
+++ b/src/include/port.h
@@ -546,6 +546,9 @@ extern int	pg_mkdir_p(char *path, int omode);
 #else
 #define pqsignal pqsignal_be
 #endif
+
+#define PG_SIG_DFL (pqsigfunc) SIG_DFL
+#define PG_SIG_IGN (pqsigfunc) SIG_IGN
 typedef void (*pqsigfunc) (SIGNAL_ARGS);
 extern void pqsignal(int signo, pqsigfunc func);
 
diff --git a/src/interfaces/libpq/legacy-pqsignal.c b/src/interfaces/libpq/legacy-pqsignal.c
index 1285b033e1b..0735e4ee0d5 100644
--- a/src/interfaces/libpq/legacy-pqsignal.c
+++ b/src/interfaces/libpq/legacy-pqsignal.c
@@ -36,10 +36,12 @@
  * is to ensure that no in-tree code accidentally calls this version.)
  */
 #undef pqsignal
-extern pqsigfunc pqsignal(int signo, pqsigfunc func);
 
-pqsigfunc
-pqsignal(int signo, pqsigfunc func)
+typedef void (*pqsigfunc_legacy) (int postgres_signal_arg);
+extern pqsigfunc_legacy pqsignal(int signo, pqsigfunc_legacy func);
+
+pqsigfunc_legacy
+pqsignal(int signo, pqsigfunc_legacy func)
 {
 #ifndef WIN32
 	struct sigaction act,
diff --git a/src/port/pqsignal.c b/src/port/pqsignal.c
index 8841464b5cb..2b39be99f94 100644
--- a/src/port/pqsignal.c
+++ b/src/port/pqsignal.c
@@ -63,6 +63,14 @@
 #define PG_NSIG (64)			/* XXX: wild guess */
 #endif
 
+#if !(defined(WIN32) && defined(FRONTEND))
+#define USE_SIGACTION
+#endif
+
+#if defined(USE_SIGACTION) && defined(HAVE_SA_SIGINFO)
+#define USE_SIGINFO
+#endif
+
 /* Check a couple of common signals to make sure PG_NSIG is accurate. */
 StaticAssertDecl(SIGUSR2 < PG_NSIG, "SIGUSR2 >= PG_NSIG");
 StaticAssertDecl(SIGHUP < PG_NSIG, "SIGHUP >= PG_NSIG");
@@ -82,19 +90,16 @@ static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
  *
  * This wrapper also handles restoring the value of errno.
  */
-#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+#ifdef USE_SIGACTION
 static void
-wrapper_handler(int signo, siginfo_t * info, void *context)
+wrapper_handler(int postgres_signal_arg, siginfo_t *info, void *context)
 #else
 static void
-wrapper_handler(SIGNAL_ARGS)
+wrapper_handler(int postgres_signal_arg)
 #endif
 {
 	int			save_errno = errno;
-#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
-	/* SA_SIGINFO signature uses signo, not SIGNAL_ARGS macro */
-	int			postgres_signal_arg = signo;
-#endif
+	pg_signal_info pg_info;
 
 	Assert(postgres_signal_arg > 0);
 	Assert(postgres_signal_arg < PG_NSIG);
@@ -110,21 +115,32 @@ wrapper_handler(SIGNAL_ARGS)
 
 	if (unlikely(MyProcPid != (int) getpid()))
 	{
-		pqsignal(postgres_signal_arg, SIG_DFL);
+		pqsignal(postgres_signal_arg, PG_SIG_DFL);
 		raise(postgres_signal_arg);
 		return;
 	}
+#endif
 
 #ifdef HAVE_SA_SIGINFO
-	if (signo == SIGTERM && info)
-	{
-		ProcDieSenderPid = info->si_pid;
-		ProcDieSenderUid = info->si_uid;
-	}
-#endif
+
+	/*
+	 * If supported by the system, forward interesting information from the
+	 * system's extended signal information to our platform independent
+	 * format.
+	 */
+	pg_info.pid = info->si_pid;
+	pg_info.uid = info->si_uid;
+#else
+
+	/*
+	 * Otherwise forward values indicating that we do not have the
+	 * information.
+	 */
+	pg_info.pid = 0;
+	pg_info.uid = 0;
 #endif
 
-	(*pqsignal_handlers[postgres_signal_arg]) (postgres_signal_arg);
+	(*pqsignal_handlers[postgres_signal_arg]) (postgres_signal_arg, &pg_info);
 
 	errno = save_errno;
 }
@@ -139,33 +155,44 @@ wrapper_handler(SIGNAL_ARGS)
 void
 pqsignal(int signo, pqsigfunc func)
 {
-#if !(defined(WIN32) && defined(FRONTEND))
+#ifdef USE_SIGACTION
 	struct sigaction act;
 #endif
-	bool		use_wrapper = false;
+	bool		is_ign = func == PG_SIG_IGN;
+	bool		is_dfl = func == PG_SIG_DFL;
 
 	Assert(signo > 0);
 	Assert(signo < PG_NSIG);
 
-	if (func != SIG_IGN && func != SIG_DFL)
+	/* set up indirection handler */
+	if (!(is_ign || is_dfl))
 	{
 		pqsignal_handlers[signo] = func;	/* assumed atomic */
-		use_wrapper = true;
 	}
 
-#if !(defined(WIN32) && defined(FRONTEND))
+	/*
+	 * Configure system to either ignore/reset the signal handler, or to
+	 * forward it to wrapper_handler.
+	 */
+#ifdef USE_SIGACTION
 	sigemptyset(&act.sa_mask);
 	act.sa_flags = SA_RESTART;
-#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
-	if (use_wrapper)
+
+	if (is_ign)
+		act.sa_handler = SIG_IGN;
+	else if (is_dfl)
+		act.sa_handler = SIG_DFL;
+
+#ifdef USE_SIGINFO
+	if (!(is_ign || is_dfl))
 	{
 		act.sa_sigaction = wrapper_handler;
 		act.sa_flags |= SA_SIGINFO;
 	}
 	else
-		act.sa_handler = func;
 #else
-	act.sa_handler = use_wrapper ? wrapper_handler : func;
+	else
+		act.sa_handler = wrapper_handler;
 #endif
 
 #ifdef SA_NOCLDSTOP
diff --git a/src/test/regress/pg_regress.c b/src/test/regress/pg_regress.c
index 9a918156437..a554542aa2a 100644
--- a/src/test/regress/pg_regress.c
+++ b/src/test/regress/pg_regress.c
@@ -492,7 +492,7 @@ signal_remove_temp(SIGNAL_ARGS)
 {
 	remove_temp();
 
-	pqsignal(postgres_signal_arg, SIG_DFL);
+	pqsignal(postgres_signal_arg, PG_SIG_DFL);
 	raise(postgres_signal_arg);
 }
 
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index e9430e07b36..97f1e474212 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -4022,6 +4022,7 @@ pg_sha224_ctx
 pg_sha256_ctx
 pg_sha384_ctx
 pg_sha512_ctx
+pg_signal_info
 pg_snapshot
 pg_special_case
 pg_stack_base_t
-- 
2.43.0



^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-09 14:00  Andres Freund <andres@anarazel.de>
  parent: Andrew Dunstan <andrew@dunslane.net>
  1 sibling, 0 replies; 54+ messages in thread

From: Andres Freund @ 2026-04-09 14:00 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Jim Jones <jim.jones@uni-muenster.de>; Chao Li <li.evan.chao@gmail.com>; Jakub Wartak <jakub.wartak@enterprisedb.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2026-04-09 06:59:39 -0400, Andrew Dunstan wrote:
> On 2026-04-08 We 1:01 PM, Andres Freund wrote:
> > Hi,
> > 
> > Attached is a very rough first draft for how I think this needs to look like.
> > 
> > Basically, SIGNAL_INFO always will pass both the signal number and extended
> > information along to the signal handler. The extended information is a
> > postgres specific struct. If the platform can't provide the extended
> > information, the values are instead set to some default value indicating that
> > the information is not known.
> > 
> > With that die() (and also StatementCancelHandler, ...) can just set whatever
> > globals it wants, without pqsignal.c needing to know about it.
> > 
> > It also allows us to extend the amount of information in the future. E.g. I'd
> > like to log the reason for a segfault (could e.g. be an OOM kill or an umapped
> > region) to stderr.
> > 
> > The annoying thing about it is needing to change nearly all the existing
> > references to SIG_IGN/SIG_DFL, to avoid warnings due to mismatched types.
> 
> 
> I agree that's annoying. The only way around it I found was via some casting
> to/from void* that I suspect you would find a cure worse than the disease.

Yea, I think it'd be worse. It's also what I had tried first.


> I reworked your patch slightly. This version fixes the translatability issue
> you raised earlier, makes the TAP test from the original commit more robust,
> and  tries to resolve your XXX issue by moving the assignment of
> ProcDieSenderPid/Uid inside the "if (!proc_exit_inprogress)" block.

I think Chao's point about needing to initialize uid to a better unset value
also needs to be fixed, at least.

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-09 14:47  Andres Freund <andres@anarazel.de>
  parent: Chao Li <li.evan.chao@gmail.com>
  0 siblings, 1 reply; 54+ messages in thread

From: Andres Freund @ 2026-04-09 14:47 UTC (permalink / raw)
  To: Chao Li <li.evan.chao@gmail.com>; +Cc: Jim Jones <jim.jones@uni-muenster.de>; Andrew Dunstan <andrew@dunslane.net>; Jakub Wartak <jakub.wartak@enterprisedb.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi,

On 2026-04-09 14:14:23 +0800, Chao Li wrote:
> > For uid, 0 is usually a valid value for root. So using 0 as the “unknown” value seems a bit awkward. Maybe we should instead document something like "uid is only meaningful when pid is not 0".
> > 
> 
> Forgot to mention, I got a lot of compile warnings, for example:
> ```
> parallel.c:1052:20: warning: cast from 'void (*)(int)' to 'pqsigfunc' (aka 'void (*)(int, struct pg_signal_info *)') converts to incompatible function type [-Wcast-function-type-mismatch]
>  1052 |         pqsignal(SIGPIPE, PG_SIG_IGN);
>       |                           ^~~~~~~~~~
> ../../../src/include/port.h:551:20: note: expanded from macro 'PG_SIG_IGN'
>   551 | #define PG_SIG_IGN (pqsigfunc) SIG_IGN
>       |                    ^~~~~~~~~~~~~~~~~~~
> 4 warnings generated.
> ```

That's an annoying warning, GAH. Can't imagine this is the only thing it
complains about. Yes, compiler, I put a cast there, because I did actually
want to cast, thanks.

I guess we'll have to define PG_SIG_IGN to 1 and PG_SIG_DFL to 0 ourselves.

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-10 06:18  Chao Li <li.evan.chao@gmail.com>
  parent: Andres Freund <andres@anarazel.de>
  0 siblings, 0 replies; 54+ messages in thread

From: Chao Li @ 2026-04-10 06:18 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: Jim Jones <jim.jones@uni-muenster.de>; Andrew Dunstan <andrew@dunslane.net>; Jakub Wartak <jakub.wartak@enterprisedb.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>



> On Apr 9, 2026, at 22:47, Andres Freund <andres@anarazel.de> wrote:
> 
> Hi,
> 
> On 2026-04-09 14:14:23 +0800, Chao Li wrote:
>>> For uid, 0 is usually a valid value for root. So using 0 as the “unknown” value seems a bit awkward. Maybe we should instead document something like "uid is only meaningful when pid is not 0".
>>> 
>> 
>> Forgot to mention, I got a lot of compile warnings, for example:
>> ```
>> parallel.c:1052:20: warning: cast from 'void (*)(int)' to 'pqsigfunc' (aka 'void (*)(int, struct pg_signal_info *)') converts to incompatible function type [-Wcast-function-type-mismatch]
>> 1052 |         pqsignal(SIGPIPE, PG_SIG_IGN);
>>      |                           ^~~~~~~~~~
>> ../../../src/include/port.h:551:20: note: expanded from macro 'PG_SIG_IGN'
>>  551 | #define PG_SIG_IGN (pqsigfunc) SIG_IGN
>>      |                    ^~~~~~~~~~~~~~~~~~~
>> 4 warnings generated.
>> ```
> 
> That's an annoying warning, GAH. Can't imagine this is the only thing it
> complains about. Yes, compiler, I put a cast there, because I did actually
> want to cast, thanks.
> 
> I guess we'll have to define PG_SIG_IGN to 1 and PG_SIG_DFL to 0 ourselves.
> 
> Greetings,
> 
> Andres Freund

I think PG already has pg_funcptr_t to treat this case, this change eliminates the warnings for me:
```
chaol@ChaodeMacBook-Air postgresql % git diff
diff --git a/src/include/port.h b/src/include/port.h
index 7db476d7b01..c029878c6be 100644
--- a/src/include/port.h
+++ b/src/include/port.h
@@ -547,8 +547,8 @@ extern int  pg_mkdir_p(char *path, int omode);
 #define pqsignal pqsignal_be
 #endif

-#define PG_SIG_DFL (pqsigfunc) SIG_DFL
-#define PG_SIG_IGN (pqsigfunc) SIG_IGN
+#define PG_SIG_DFL (pqsigfunc) (pg_funcptr_t) SIG_DFL
+#define PG_SIG_IGN (pqsigfunc) (pg_funcptr_t) SIG_IGN
 typedef void (*pqsigfunc) (SIGNAL_ARGS);
 extern void pqsignal(int signo, pqsigfunc func);
```

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/









^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-10 07:40  Chao Li <li.evan.chao@gmail.com>
  parent: Andrew Dunstan <andrew@dunslane.net>
  1 sibling, 1 reply; 54+ messages in thread

From: Chao Li @ 2026-04-10 07:40 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; Jakub Wartak <jakub.wartak@enterprisedb.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>



> On Apr 9, 2026, at 18:59, Andrew Dunstan <andrew@dunslane.net> wrote:
> 
> 
> On 2026-04-08 We 1:01 PM, Andres Freund wrote:
>> Hi,
>> 
>> Attached is a very rough first draft for how I think this needs to look like.
>> 
>> Basically, SIGNAL_INFO always will pass both the signal number and extended
>> information along to the signal handler. The extended information is a
>> postgres specific struct. If the platform can't provide the extended
>> information, the values are instead set to some default value indicating that
>> the information is not known.
>> 
>> With that die() (and also StatementCancelHandler, ...) can just set whatever
>> globals it wants, without pqsignal.c needing to know about it.
>> 
>> It also allows us to extend the amount of information in the future. E.g. I'd
>> like to log the reason for a segfault (could e.g. be an OOM kill or an umapped
>> region) to stderr.
>> 
>> The annoying thing about it is needing to change nearly all the existing
>> references to SIG_IGN/SIG_DFL, to avoid warnings due to mismatched types.
> 
> I agree that's annoying. The only way around it I found was via some casting to/from void* that I suspect you would find a cure worse than the disease.
> I reworked your patch slightly. This version fixes the translatability issue you raised earlier, makes the TAP test from the original commit more robust, and  tries to resolve your XXX issue by moving the assignment of ProcDieSenderPid/Uid inside the "if (!proc_exit_inprogress)" block.
> 
> cheers
> 
> andrew
> 
> 
> 
> --
> Andrew Dunstan
> EDB: https://www.enterprisedb.com
> 
> <0001-Rework-signal-sender-errdetail-to-pass-info-via-hand.patch>

I reviewed this version. Besides the compile warning and uid 0 issues, I got a few more comments, so I try to put them all together as below.

1 - compile warnings
As talked in an earlier email, this eliminates the compile warnings for me:
```
chaol@ChaodeMacBook-Air postgresql % git diff
diff --git a/src/include/port.h b/src/include/port.h
index 7db476d7b01..c029878c6be 100644
--- a/src/include/port.h
+++ b/src/include/port.h
@@ -547,8 +547,8 @@ extern int  pg_mkdir_p(char *path, int omode);
#define pqsignal pqsignal_be
#endif

-#define PG_SIG_DFL (pqsigfunc) SIG_DFL
-#define PG_SIG_IGN (pqsigfunc) SIG_IGN
+#define PG_SIG_DFL (pqsigfunc) (pg_funcptr_t) SIG_DFL
+#define PG_SIG_IGN (pqsigfunc) (pg_funcptr_t) SIG_IGN
typedef void (*pqsigfunc) (SIGNAL_ARGS);
extern void pqsignal(int signo, pqsigfunc func);
```

2 - uid 0 problem
```
+typedef struct pg_signal_info
+{
+	pid_t		pid;			/* pid of sending process or 0 if unknown */
+	uid_t		uid;			/* uid of sending process or 0 if unknown */
+} pg_signal_info;
```

I think we can mention that “uid” is only meaningful when pid is set.

3 Also for the struct pg_signal_info. As the struct name is generic in order to hold some more fields in the future, does it make sense to rename “pid” to “sender_pid” and “uid” to “sender_pid” to reflect their actual meanings? I am thinking that, some other pid/uid might be added to this struct in the future.

4
```
-#ifndef SIGNAL_ARGS
-#define SIGNAL_ARGS  int postgres_signal_arg
-#endif
+/*
+ * The following is used as the arg list for signal handlers. These days we
+ * use the same argument to all signal handlers and hide the difference
+ * between platforms in wrapper functions.
+ *
+ * SIGNAL_ARGS just exists separately from the pqsignal() definition for
+ * historical reasons.
+ */
+#define SIGNAL_ARGS  int postgres_signal_arg, pg_signal_info *pg_siginfo
```

Given we now define new PG_SIG_IGN and PG_SIG_DFL, does it make sense to rename SIGNAL_ARGS to PG_SIGNAL_ARGS?

5
```
+	pg_info.uid = 0;
```

If you take comment 2, then when unavailable, we can just don’t assign anything to pg_info.uid. Or "(uid_t)-1", maybe.

6
```
+#define SIGNAL_ARGS  int postgres_signal_arg, pg_signal_info *pg_siginfo
```

Maybe pg_siginfo can be const.

7
```
+						 errdetail("The transaction has already committed locally, but might not have been replicated to the standby. Signal sent by PID %d, UID %d.”,
```

Per https://www.postgresql.org/docs/current/error-style-guide.html, for hint and detail messages, “Put two spaces after the period if another sentence follows”.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/









^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-14 10:40  Jakub Wartak <jakub.wartak@enterprisedb.com>
  parent: Chao Li <li.evan.chao@gmail.com>
  0 siblings, 1 reply; 54+ messages in thread

From: Jakub Wartak @ 2026-04-14 10:40 UTC (permalink / raw)
  To: Chao Li <li.evan.chao@gmail.com>; +Cc: Andrew Dunstan <andrew@dunslane.net>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Hi Andres, Andrew, Chao

thanks for putting so much effort into enhancing the the previous implementation
of this code. Earlier I was not aware of potential problems involved.

On Fri, Apr 10, 2026 at 9:41 AM Chao Li <li.evan.chao@gmail.com> wrote:
>
>
>
> > On Apr 9, 2026, at 18:59, Andrew Dunstan <andrew@dunslane.net> wrote:
> >
> >
> > On 2026-04-08 We 1:01 PM, Andres Freund wrote:
> >> Hi,
> >>
> >> Attached is a very rough first draft for how I think this needs to look like.
> >>
> >> Basically, SIGNAL_INFO always will pass both the signal number and extended
> >> information along to the signal handler. The extended information is a
> >> postgres specific struct. If the platform can't provide the extended
> >> information, the values are instead set to some default value indicating that
> >> the information is not known.
> >>
> >> With that die() (and also StatementCancelHandler, ...) can just set whatever
> >> globals it wants, without pqsignal.c needing to know about it.
> >>
> >> It also allows us to extend the amount of information in the future. E.g. I'd
> >> like to log the reason for a segfault (could e.g. be an OOM kill or an umapped
> >> region) to stderr.
> >>
> >> The annoying thing about it is needing to change nearly all the existing
> >> references to SIG_IGN/SIG_DFL, to avoid warnings due to mismatched types.
> >
> > I agree that's annoying. The only way around it I found was via some casting to/from void* that I suspect you would find a cure worse than the disease.
> > I reworked your patch slightly. This version fixes the translatability issue you raised earlier, makes the TAP test from the original commit more robust, and  tries to resolve your XXX issue by moving the assignment of ProcDieSenderPid/Uid inside the "if (!proc_exit_inprogress)" block.
> >
>
> I reviewed this version. Besides the compile warning and uid 0 issues, I got a few more comments, so I try to put them all together as below.
>

TL;DR; win/mingw is really unhappy with the state of rework patch right now.
I've tried to enhance and fix it, and now it's green for default CI run and
also for mingw too. Attached 0002-fixup-win32 patch does not incorporate Chao's
all findings so far.

[..]
> 2 - uid 0 problem
> ```
> +typedef struct pg_signal_info
> +{
> +       pid_t           pid;                    /* pid of sending process or 0 if unknown */
> +       uid_t           uid;                    /* uid of sending process or 0 if unknown */
> +} pg_signal_info;
> ```
>
> I think we can mention that “uid” is only meaningful when pid is set.

[..]
> 5
> ```
> +       pg_info.uid = 0;
> ```
>
> If you take comment 2, then when unavailable, we can just don’t assign anything to pg_info.uid. Or "(uid_t)-1", maybe.
>


I. I've started from this and I vaguley remembered that I had terrible
experience
when trying to chose the proper types for those field types, but I couldn't
remind myself why, so I've gave a try of the current rework patch and got this
on Windows Server 2022, vs2019, cirrus-ci said:

[08:40:22.848] c:\cirrus\src\include\c.h(1451): error C2061: syntax
error: identifier 'pid_t'
[08:40:22.848] c:\cirrus\src\include\c.h(1452): error C2061: syntax
error: identifier 'uid'
[08:40:22.848] c:\cirrus\src\include\c.h(1452): error C2059: syntax error: ';'
[08:40:22.848] c:\cirrus\src\include\c.h(1453): error C2059: syntax error: '}'

for c.h:
  1449  typedef struct pg_signal_info
  1450  {
  1451          pid_t           pid;                    /* pid of
sending process or 0 if unknown */
  1452          uid_t           uid;                    /* uid of
sending process or 0 if unknown */
  1453  } pg_signal_info;

so maybe we should just move that typedef with SIGNAL_ARGS to after
"include of port.h" (line ~1471) in that c.h, because only then we'll have
access to:
    src/include/port/win32_port.h:typedef int pid_t;
    src/include/port/win32_port.h:typedef int uid_t;
but the problem is that port.h itself requires SIGNAL_ARGS to be defined
and that seems to be like chicken and egg problem.  I thought that just
using native "ints" could be the way to go, but the problem is that now
that uid_t can be bigger than pid_t as Linux kernel headers show this:

x86_64-linux-gnu/bits/types.h:#define   __S32_TYPE              int
x86_64-linux-gnu/bits/types.h:#define __U32_TYPE                unsigned int
x86_64-linux-gnu/bits/types.h:__STD_TYPE __UID_T_TYPE __uid_t;  /*
Type of user identifications.  */
x86_64-linux-gnu/bits/types.h:__STD_TYPE __PID_T_TYPE __pid_t;  /*
Type of process identifications.  */
x86_64-linux-gnu/bits/typesizes.h:#define __UID_T_TYPE          __U32_TYPE
x86_64-linux-gnu/bits/typesizes.h:#define __PID_T_TYPE          __S32_TYPE

so maybe do that typedef struct pg_signal_info with 2x uint32_t and that's
good enough? (it covers the ranges necessary and makes it platform compatible)

II. While we are tthis so with above uid_t of up to being u32, possibly
`volatile int ProcDieSenderUid/Pid` should be also bigger like uint32_t?
My fixup-patch does not incude it, because I don't know really.

III. As Chao said I've used:

+#define PG_SIG_DFL (pqsigfunc) (pg_funcptr_t) SIG_DFL
+#define PG_SIG_IGN (pqsigfunc) (pg_funcptr_t) SIG_IGN

IV.  Then just got lots of warnings for use_wrapper/wrapp_handler and so on

[09:27:33.602] ../src/port/pqsignal.c(206): error C2065:
'use_wrapper': undeclared identifier
[09:27:33.602] ../src/port/pqsignal.c(206): warning C4113: 'pqsigfunc'
differs in parameter lists from 'void (__cdecl *)(int)'

that's for:
   204  #else
   205          /* Forward to Windows native signal system. */
   206          if (signal(signo, use_wrapper ? wrapper_handler :
func) == SIG_ERR)
   207                  Assert(false);                  /* probably
indicates coding error */

In the end, I've ended up using wrapper_handler for the windows path there
as signal() requires function with single param.

IV. Got some further issues, and VC complained that siginfo_t is used for
USE_SIGACTION - isn't it impossible on win32? Anyway, that makes some sense,
USE_SIGINFO is not defined and we use 'siginfo_t', so something like fixes it:

@@ -90,7 +90,7 @@ static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
  *
  * This wrapper also handles restoring the value of errno.
  */
-#ifdef USE_SIGACTION
+#if defined(USE_SIGACTION) && defined(USE_SIGINFO)
 static void
 wrapper_handler(int postgres_signal_arg, siginfo_t *info, void *context)
 #else

V. Later I've stumbled on series of other problems related to
src/backend/port/win32/signal.c (it also uses SIG_DFL but not PG_SIG_DFL and
stil somewhat references pgsigfunc, so those changes seemed to impact it).

Also there was:
[10:37:02.824] ../src/backend/port/win32/signal.c(154): error C2198:
'sig': too few arguments for call

so I've fixed with adding nodata struct there and:
@@ -151,7 +154,7 @@ pgwin32_dispatch_queued_signals(void)
                                                block_mask |= sigmask(i);

                                        sigprocmask(SIG_BLOCK,
&block_mask, &save_mask);
-                                       sig(i);
+                                       sig(i, &nodata);
                                        sigprocmask(SIG_SETMASK,
&save_mask, NULL);

VI. Possibly we could rename USE_SIGACTION define because at least to me it
is confusing to me to reason and communicate about in terms of win32 context
on win32 do we do have it or not? (it can be both ways):
* win32 C API doesnt have it
* PG does have sigaction win32 wrapper with override macro
  #define sigaction.. pqsigaction..
* however src/include/libpq/pqsignal.h says "sa_sigaction not yet implemented"
  for it (so with USE_SIGACTION are we talking about sa_sigaction field memeber
  that it's not used or about sigaction function?)

VII. FWIW, I've also removed superflous "else"
 #ifdef USE_SIGINFO
        if (!(is_ign || is_dfl))
        {
                act.sa_sigaction = wrapper_handler;
                act.sa_flags |= SA_SIGINFO;
        }
-       else
 #else


-J.

Attachments:

  [text/x-patch] 0002-fixup-win32.patch (4.8K, ../../CAKZiRmws3_4xemjzP9kyp=co=gc1GXoZ2VtqZzGuO9-tN8ok8Q@mail.gmail.com/2-0002-fixup-win32.patch)
  download | inline diff:
From 6886e3c0f6ca692ca8c50bc1886d7e60b7c9508a Mon Sep 17 00:00:00 2001
From: Jakub Wartak <jakub.wartak@enterprisedb.com>
Date: Mon, 13 Apr 2026 11:24:20 +0200
Subject: [PATCH 2/2] fixup-win32

---
 src/backend/port/win32/signal.c | 13 ++++++++-----
 src/include/c.h                 |  5 +++--
 src/include/port.h              |  4 ++--
 src/port/pqsignal.c             | 24 +++++++++++++++++-------
 4 files changed, 30 insertions(+), 16 deletions(-)

diff --git a/src/backend/port/win32/signal.c b/src/backend/port/win32/signal.c
index 465d69a1f28..d7cdb1cd1fe 100644
--- a/src/backend/port/win32/signal.c
+++ b/src/backend/port/win32/signal.c
@@ -88,7 +88,7 @@ pgwin32_signal_initialize(void)
 		pg_signal_array[i].sa_handler = SIG_DFL;
 		pg_signal_array[i].sa_mask = 0;
 		pg_signal_array[i].sa_flags = 0;
-		pg_signal_defaults[i] = SIG_IGN;
+		pg_signal_defaults[i] = PG_SIG_IGN;
 	}
 	pg_signal_mask = 0;
 	pg_signal_queue = 0;
@@ -134,15 +134,18 @@ pgwin32_dispatch_queued_signals(void)
 			{
 				/* Execute this signal */
 				struct sigaction *act = &pg_signal_array[i];
-				pqsigfunc	sig = act->sa_handler;
+				pqsigfunc	sig = (pqsigfunc)(pg_funcptr_t) act->sa_handler;
 
-				if (sig == SIG_DFL)
+				if (sig == PG_SIG_DFL)
 					sig = pg_signal_defaults[i];
 				pg_signal_queue &= ~sigmask(i);
-				if (sig != SIG_ERR && sig != SIG_IGN && sig != SIG_DFL)
+				if (sig != (pqsigfunc)(pg_funcptr_t)SIG_ERR && sig != PG_SIG_IGN && sig != PG_SIG_DFL)
 				{
 					sigset_t	block_mask;
 					sigset_t	save_mask;
+					struct pg_signal_info nodata;
+					nodata.pid = 0;
+					nodata.uid = 0;
 
 					LeaveCriticalSection(&pg_signal_crit_sec);
 
@@ -151,7 +154,7 @@ pgwin32_dispatch_queued_signals(void)
 						block_mask |= sigmask(i);
 
 					sigprocmask(SIG_BLOCK, &block_mask, &save_mask);
-					sig(i);
+					sig(i, &nodata);
 					sigprocmask(SIG_SETMASK, &save_mask, NULL);
 
 					EnterCriticalSection(&pg_signal_crit_sec);
diff --git a/src/include/c.h b/src/include/c.h
index 77ea73cc707..b43ac8e995d 100644
--- a/src/include/c.h
+++ b/src/include/c.h
@@ -1446,10 +1446,11 @@ extern int	fdatasync(int fd);
  * or a field does not apply to the signal, the value is instead reset to the
  * documented default value.
  */
+
 typedef struct pg_signal_info
 {
-	pid_t		pid;			/* pid of sending process or 0 if unknown */
-	uid_t		uid;			/* uid of sending process or 0 if unknown */
+	uint32_t		pid;			/* pid of sending process or 0 if unknown */
+	uint32_t		uid;			/* uid of sending process or 0 if unknown */
 } pg_signal_info;
 
 /*
diff --git a/src/include/port.h b/src/include/port.h
index 7db476d7b01..c029878c6be 100644
--- a/src/include/port.h
+++ b/src/include/port.h
@@ -547,8 +547,8 @@ extern int	pg_mkdir_p(char *path, int omode);
 #define pqsignal pqsignal_be
 #endif
 
-#define PG_SIG_DFL (pqsigfunc) SIG_DFL
-#define PG_SIG_IGN (pqsigfunc) SIG_IGN
+#define PG_SIG_DFL (pqsigfunc) (pg_funcptr_t) SIG_DFL
+#define PG_SIG_IGN (pqsigfunc) (pg_funcptr_t) SIG_IGN
 typedef void (*pqsigfunc) (SIGNAL_ARGS);
 extern void pqsignal(int signo, pqsigfunc func);
 
diff --git a/src/port/pqsignal.c b/src/port/pqsignal.c
index 2b39be99f94..dfa5acbb139 100644
--- a/src/port/pqsignal.c
+++ b/src/port/pqsignal.c
@@ -90,10 +90,10 @@ static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
  *
  * This wrapper also handles restoring the value of errno.
  */
-#ifdef USE_SIGACTION
+#if defined(USE_SIGACTION) && defined(USE_SIGINFO)
 static void
 wrapper_handler(int postgres_signal_arg, siginfo_t *info, void *context)
-#else
+#else /* no USE_SIGINFO */
 static void
 wrapper_handler(int postgres_signal_arg)
 #endif
@@ -157,6 +157,8 @@ pqsignal(int signo, pqsigfunc func)
 {
 #ifdef USE_SIGACTION
 	struct sigaction act;
+#else
+	void (*wrapper_func_ptr)(int);
 #endif
 	bool		is_ign = func == PG_SIG_IGN;
 	bool		is_dfl = func == PG_SIG_DFL;
@@ -182,14 +184,12 @@ pqsignal(int signo, pqsigfunc func)
 		act.sa_handler = SIG_IGN;
 	else if (is_dfl)
 		act.sa_handler = SIG_DFL;
-
 #ifdef USE_SIGINFO
 	if (!(is_ign || is_dfl))
 	{
 		act.sa_sigaction = wrapper_handler;
 		act.sa_flags |= SA_SIGINFO;
 	}
-	else
 #else
 	else
 		act.sa_handler = wrapper_handler;
@@ -201,9 +201,19 @@ pqsignal(int signo, pqsigfunc func)
 #endif
 	if (sigaction(signo, &act, NULL) < 0)
 		Assert(false);			/* probably indicates coding error */
-#else
-	/* Forward to Windows native signal system. */
-	if (signal(signo, use_wrapper ? wrapper_handler : func) == SIG_ERR)
+#else /* no USE_SIGACTION */
+	/*
+	 * Forward to Windows native signal system, we need to send this though
+	 * wrapper handler as it it needs to take single argument only.
+	 */
+	if(is_ign)
+		wrapper_func_ptr = SIG_IGN;
+	else if (is_dfl)
+		wrapper_func_ptr = SIG_DFL;
+	else
+		wrapper_func_ptr = wrapper_handler;
+
+	if (signal(signo, wrapper_func_ptr) == SIG_ERR)
 		Assert(false);			/* probably indicates coding error */
 #endif
 }
-- 
2.43.0



  [text/x-patch] 0001-Rework-signal-sender-errdetail-to-pass-info-via-hand.patch (34.3K, ../../CAKZiRmws3_4xemjzP9kyp=co=gc1GXoZ2VtqZzGuO9-tN8ok8Q@mail.gmail.com/3-0001-Rework-signal-sender-errdetail-to-pass-info-via-hand.patch)
  download | inline diff:
From a27f1abd54ac47e3356becc06f98355a9bbd22fc Mon Sep 17 00:00:00 2001
From: Andrew Dunstan <andrew@dunslane.net>
Date: Wed, 8 Apr 2026 16:09:35 -0400
Subject: [PATCH 1/2] Rework signal-sender errdetail to pass info via handler
 arguments.

Commit 095c9d4cf06 added errdetail() reporting of the PID and UID of
the process that sent a termination signal.  However, as noted by
Andres Freund, the implementation had architectural problems:

1. wrapper_handler() in pqsignal.c contained SIGTERM-specific logic
   (setting ProcDieSenderPid/Uid), violating its role as a generic
   signal dispatch wrapper.

2. Using globals to pass sender info between wrapper_handler and the
   real handler is unsafe when signals nest on some platforms.

3. The syncrep.c errdetail used psprintf() to conditionally embed
   text via %s, breaking translatability.

Adopt the approach proposed by Andres Freund: introduce a
pg_signal_info struct that is passed as an argument to all signal
handlers via the SIGNAL_ARGS macro.  wrapper_handler populates it
from siginfo_t when SA_SIGINFO is available, or with zeros otherwise.
This keeps wrapper_handler fully generic and avoids any globals for
passing signal metadata.

Since pqsigfunc now has a different signature from the system's
signal handler type, SIG_IGN and SIG_DFL can no longer be passed
directly to pqsignal().  Introduce PG_SIG_IGN and PG_SIG_DFL macros
that cast to the new pqsigfunc type, and update all call sites.
The legacy pqsignal() in libpq retains its original signature via
a local typedef.

Only die() reads pg_siginfo today, copying the sender PID/UID into
ProcDieSenderPid/Uid for later use by ProcessInterrupts().  Only the
first SIGTERM's sender info is recorded.

Also fix the syncrep.c translatability issue by using separate ereport
calls with complete, independently translatable errdetail strings.

Also make the psql TAP test require the DETAIL line on platforms with
SA_SIGINFO, rather than making it unconditionally optional.

Author: Andres Freund <andres@anarazel.de>
Reviewed-by: Andrew Dunstan <andrew@dunslane.net>
Discussion: https://postgr.es/m/cwyyryh2veejuxbj5ifzyaejw7jhhqc5mrdeq56xckknsdecn2@6hzfcxde2nm5
Discussion: https://postgr.es/m/jygesyr7mwg7ovdbxpmjvvbi3hccptpkcreqb645h7f56puwbz@hmkkwi3melfe
---
 src/backend/bootstrap/bootstrap.c           |  8 +--
 src/backend/postmaster/autovacuum.c         | 10 +--
 src/backend/postmaster/bgworker.c           | 14 ++--
 src/backend/postmaster/bgwriter.c           | 10 +--
 src/backend/postmaster/checkpointer.c       |  8 +--
 src/backend/postmaster/datachecksum_state.c |  2 +-
 src/backend/postmaster/pgarch.c             |  8 +--
 src/backend/postmaster/postmaster.c         | 12 ++--
 src/backend/postmaster/startup.c            |  6 +-
 src/backend/postmaster/syslogger.c          | 14 ++--
 src/backend/postmaster/walsummarizer.c      | 10 +--
 src/backend/postmaster/walwriter.c          | 10 +--
 src/backend/replication/logical/slotsync.c  |  6 +-
 src/backend/replication/syncrep.c           | 28 ++++----
 src/backend/replication/walreceiver.c       | 10 +--
 src/backend/replication/walsender.c         |  4 +-
 src/backend/storage/aio/method_worker.c     |  6 +-
 src/backend/storage/file/fd.c               |  4 +-
 src/backend/storage/ipc/waiteventset.c      |  2 +-
 src/backend/tcop/postgres.c                 | 19 ++++--
 src/bin/initdb/initdb.c                     |  4 +-
 src/bin/pg_ctl/pg_ctl.c                     |  2 +-
 src/bin/pg_dump/parallel.c                  |  8 +--
 src/bin/psql/t/001_basic.pl                 |  5 +-
 src/fe_utils/print.c                        |  4 +-
 src/include/c.h                             | 27 +++++---
 src/include/port.h                          |  3 +
 src/interfaces/libpq/legacy-pqsignal.c      |  8 ++-
 src/port/pqsignal.c                         | 75 ++++++++++++++-------
 src/test/regress/pg_regress.c               |  2 +-
 src/tools/pgindent/typedefs.list            |  1 +
 31 files changed, 191 insertions(+), 139 deletions(-)

diff --git a/src/backend/bootstrap/bootstrap.c b/src/backend/bootstrap/bootstrap.c
index a4af7bf8fad..b0dcd9876c5 100644
--- a/src/backend/bootstrap/bootstrap.c
+++ b/src/backend/bootstrap/bootstrap.c
@@ -463,10 +463,10 @@ bootstrap_signals(void)
 	 * mode; "curl up and die" is a sufficient response for all these cases.
 	 * Let's set that handling explicitly, as documentation if nothing else.
 	 */
-	pqsignal(SIGHUP, SIG_DFL);
-	pqsignal(SIGINT, SIG_DFL);
-	pqsignal(SIGTERM, SIG_DFL);
-	pqsignal(SIGQUIT, SIG_DFL);
+	pqsignal(SIGHUP, PG_SIG_DFL);
+	pqsignal(SIGINT, PG_SIG_DFL);
+	pqsignal(SIGTERM, PG_SIG_DFL);
+	pqsignal(SIGQUIT, PG_SIG_DFL);
 }
 
 /* ----------------------------------------------------------------
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index 82061247988..680db664be4 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -445,11 +445,11 @@ AutoVacLauncherMain(const void *startup_data, size_t startup_data_len)
 
 	InitializeTimeouts();		/* establishes SIGALRM handler */
 
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, avl_sigusr2_handler);
 	pqsignal(SIGFPE, FloatExceptionHandler);
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Create a per-backend PGPROC struct in shared memory.  We must do this
@@ -1456,11 +1456,11 @@ AutoVacWorkerMain(const void *startup_data, size_t startup_data_len)
 
 	InitializeTimeouts();		/* establishes SIGALRM handler */
 
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 	pqsignal(SIGFPE, FloatExceptionHandler);
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Create a per-backend PGPROC struct in shared memory.  We must do this
diff --git a/src/backend/postmaster/bgworker.c b/src/backend/postmaster/bgworker.c
index 3914d22a514..2e4acad4f00 100644
--- a/src/backend/postmaster/bgworker.c
+++ b/src/backend/postmaster/bgworker.c
@@ -785,19 +785,19 @@ BackgroundWorkerMain(const void *startup_data, size_t startup_data_len)
 	}
 	else
 	{
-		pqsignal(SIGINT, SIG_IGN);
-		pqsignal(SIGUSR1, SIG_IGN);
-		pqsignal(SIGFPE, SIG_IGN);
+		pqsignal(SIGINT, PG_SIG_IGN);
+		pqsignal(SIGUSR1, PG_SIG_IGN);
+		pqsignal(SIGFPE, PG_SIG_IGN);
 	}
 	pqsignal(SIGTERM, die);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGHUP, SIG_IGN);
+	pqsignal(SIGHUP, PG_SIG_IGN);
 
 	InitializeTimeouts();		/* establishes SIGALRM handler */
 
-	pqsignal(SIGPIPE, SIG_IGN);
-	pqsignal(SIGUSR2, SIG_IGN);
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * If an exception is encountered, processing resumes here.
diff --git a/src/backend/postmaster/bgwriter.c b/src/backend/postmaster/bgwriter.c
index a30de4262eb..cd1bf9d919c 100644
--- a/src/backend/postmaster/bgwriter.c
+++ b/src/backend/postmaster/bgwriter.c
@@ -101,18 +101,18 @@ BackgroundWriterMain(const void *startup_data, size_t startup_data_len)
 	 * Properly accept or ignore signals that might be sent to us.
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
-	pqsignal(SIGINT, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
 	pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * We just started, assume there has been either a shutdown or
diff --git a/src/backend/postmaster/checkpointer.c b/src/backend/postmaster/checkpointer.c
index 6b424ee610f..087120db090 100644
--- a/src/backend/postmaster/checkpointer.c
+++ b/src/backend/postmaster/checkpointer.c
@@ -223,17 +223,17 @@ CheckpointerMain(const void *startup_data, size_t startup_data_len)
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
 	pqsignal(SIGINT, ReqShutdownXLOG);
-	pqsignal(SIGTERM, SIG_IGN); /* ignore SIGTERM */
+	pqsignal(SIGTERM, PG_SIG_IGN);	/* ignore SIGTERM */
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, SignalHandlerForShutdownRequest);
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Initialize so that first time-driven event happens at the correct time.
diff --git a/src/backend/postmaster/datachecksum_state.c b/src/backend/postmaster/datachecksum_state.c
index 1243949eacb..18797a8ee3d 100644
--- a/src/backend/postmaster/datachecksum_state.c
+++ b/src/backend/postmaster/datachecksum_state.c
@@ -1020,7 +1020,7 @@ DataChecksumsWorkerLauncherMain(Datum arg)
 	pqsignal(SIGTERM, die);
 	pqsignal(SIGINT, launcher_cancel_handler);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 
 	BackgroundWorkerUnblockSignals();
 
diff --git a/src/backend/postmaster/pgarch.c b/src/backend/postmaster/pgarch.c
index 0a1a1149d78..0f207ac0356 100644
--- a/src/backend/postmaster/pgarch.c
+++ b/src/backend/postmaster/pgarch.c
@@ -229,16 +229,16 @@ PgArchiverMain(const void *startup_data, size_t startup_data_len)
 	 * except for SIGHUP, SIGTERM, SIGUSR1, SIGUSR2, and SIGQUIT.
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
-	pqsignal(SIGINT, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
 	pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, pgarch_waken_stop);
 
 	/* Reset some signals that are accepted by postmaster but not here */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/* Unblock signals (they were blocked when the postmaster forked us) */
 	sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
index 6e0f41d2661..b6fd332f196 100644
--- a/src/backend/postmaster/postmaster.c
+++ b/src/backend/postmaster/postmaster.c
@@ -555,8 +555,8 @@ PostmasterMain(int argc, char *argv[])
 	pqsignal(SIGINT, handle_pm_shutdown_request_signal);
 	pqsignal(SIGQUIT, handle_pm_shutdown_request_signal);
 	pqsignal(SIGTERM, handle_pm_shutdown_request_signal);
-	pqsignal(SIGALRM, SIG_IGN); /* ignored */
-	pqsignal(SIGPIPE, SIG_IGN); /* ignored */
+	pqsignal(SIGALRM, PG_SIG_IGN);	/* ignored */
+	pqsignal(SIGPIPE, PG_SIG_IGN);	/* ignored */
 	pqsignal(SIGUSR1, handle_pm_pmsignal_signal);
 	pqsignal(SIGUSR2, dummy_handler);	/* unused, reserve for children */
 	pqsignal(SIGCHLD, handle_pm_child_exit_signal);
@@ -573,15 +573,15 @@ PostmasterMain(int argc, char *argv[])
 	 * child processes should just allow the inherited settings to stand.
 	 */
 #ifdef SIGTTIN
-	pqsignal(SIGTTIN, SIG_IGN); /* ignored */
+	pqsignal(SIGTTIN, PG_SIG_IGN);	/* ignored */
 #endif
 #ifdef SIGTTOU
-	pqsignal(SIGTTOU, SIG_IGN); /* ignored */
+	pqsignal(SIGTTOU, PG_SIG_IGN);	/* ignored */
 #endif
 
 	/* ignore SIGXFSZ, so that ulimit violations work like disk full */
 #ifdef SIGXFSZ
-	pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
+	pqsignal(SIGXFSZ, PG_SIG_IGN);	/* ignored */
 #endif
 
 	/* Begin accepting signals. */
@@ -3967,7 +3967,7 @@ process_pm_pmsignal(void)
  * Dummy signal handler
  *
  * We use this for signals that we don't actually use in the postmaster,
- * but we do use in backends.  If we were to SIG_IGN such signals in the
+ * but we do use in backends.  If we were to PG_SIG_IGN such signals in the
  * postmaster, then a newly started backend might drop a signal that arrives
  * before it's able to reconfigure its signal processing.  (See notes in
  * tcop/postgres.c.)
diff --git a/src/backend/postmaster/startup.c b/src/backend/postmaster/startup.c
index cdbe53dd262..b46bac681fe 100644
--- a/src/backend/postmaster/startup.c
+++ b/src/backend/postmaster/startup.c
@@ -226,18 +226,18 @@ StartupProcessMain(const void *startup_data, size_t startup_data_len)
 	 * Properly accept or ignore signals the postmaster might send us.
 	 */
 	pqsignal(SIGHUP, StartupProcSigHupHandler); /* reload config file */
-	pqsignal(SIGINT, SIG_IGN);	/* ignore query cancel */
+	pqsignal(SIGINT, PG_SIG_IGN);	/* ignore query cancel */
 	pqsignal(SIGTERM, StartupProcShutdownHandler);	/* request shutdown */
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
 	InitializeTimeouts();		/* establishes SIGALRM handler */
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, StartupProcTriggerHandler);
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Register timeouts needed for standby mode
diff --git a/src/backend/postmaster/syslogger.c b/src/backend/postmaster/syslogger.c
index 0c2a7bc8578..acfe0a01715 100644
--- a/src/backend/postmaster/syslogger.c
+++ b/src/backend/postmaster/syslogger.c
@@ -276,18 +276,18 @@ SysLoggerMain(const void *startup_data, size_t startup_data_len)
 
 	pqsignal(SIGHUP, SignalHandlerForConfigReload); /* set flag to read config
 													 * file */
-	pqsignal(SIGINT, SIG_IGN);
-	pqsignal(SIGTERM, SIG_IGN);
-	pqsignal(SIGQUIT, SIG_IGN);
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
+	pqsignal(SIGTERM, PG_SIG_IGN);
+	pqsignal(SIGQUIT, PG_SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, sigUsr1Handler);	/* request log rotation */
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
 
diff --git a/src/backend/postmaster/walsummarizer.c b/src/backend/postmaster/walsummarizer.c
index 20960f5b633..4f12eaf2c85 100644
--- a/src/backend/postmaster/walsummarizer.c
+++ b/src/backend/postmaster/walsummarizer.c
@@ -244,13 +244,13 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len)
 	 * Properly accept or ignore signals the postmaster might send us
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
-	pqsignal(SIGINT, SIG_IGN);	/* no query to cancel */
+	pqsignal(SIGINT, PG_SIG_IGN);	/* no query to cancel */
 	pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN); /* not used */
+	pqsignal(SIGUSR2, PG_SIG_IGN);	/* not used */
 
 	/* Advertise ourselves. */
 	on_shmem_exit(WalSummarizerShutdown, (Datum) 0);
@@ -267,7 +267,7 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len)
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * If an exception is encountered, processing resumes here.
diff --git a/src/backend/postmaster/walwriter.c b/src/backend/postmaster/walwriter.c
index 9cd86ad7022..af24d05c542 100644
--- a/src/backend/postmaster/walwriter.c
+++ b/src/backend/postmaster/walwriter.c
@@ -101,18 +101,18 @@ WalWriterMain(const void *startup_data, size_t startup_data_len)
 	 * Properly accept or ignore signals the postmaster might send us
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
-	pqsignal(SIGINT, SIG_IGN);	/* no query to cancel */
+	pqsignal(SIGINT, PG_SIG_IGN);	/* no query to cancel */
 	pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN); /* not used */
+	pqsignal(SIGUSR2, PG_SIG_IGN);	/* not used */
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Create a memory context that we will do all our work in.  We do this so
diff --git a/src/backend/replication/logical/slotsync.c b/src/backend/replication/logical/slotsync.c
index d01b401cd28..ad3747e598c 100644
--- a/src/backend/replication/logical/slotsync.c
+++ b/src/backend/replication/logical/slotsync.c
@@ -1620,9 +1620,9 @@ ReplSlotSyncWorkerMain(const void *startup_data, size_t startup_data_len)
 	pqsignal(SIGTERM, die);
 	pqsignal(SIGFPE, FloatExceptionHandler);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	check_and_set_sync_info(MyProcPid);
 
diff --git a/src/backend/replication/syncrep.c b/src/backend/replication/syncrep.c
index 46a778f0917..896ba45412d 100644
--- a/src/backend/replication/syncrep.c
+++ b/src/backend/replication/syncrep.c
@@ -300,22 +300,18 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 		 */
 		if (ProcDiePending)
 		{
-			/*
-			 * ProcDieSenderPid/Uid are read directly from the globals here
-			 * rather than copied to locals first; a second SIGTERM could
-			 * change them between reads, but that is harmless because the
-			 * process is about to die anyway.  The signal sender detail is
-			 * inlined rather than using a separate errdetail() call because
-			 * it must be appended to the existing detail message.
-			 */
-			ereport(WARNING,
-					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.%s",
-							   ProcDieSenderPid == 0 ? "" :
-							   psprintf("\nSignal sent by PID %d, UID %d.",
-										(int) ProcDieSenderPid,
-										(int) ProcDieSenderUid))));
+			if (ProcDieSenderPid != 0)
+				ereport(WARNING,
+						(errcode(ERRCODE_ADMIN_SHUTDOWN),
+						 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
+						 errdetail("The transaction has already committed locally, but might not have been replicated to the standby. Signal sent by PID %d, UID %d.",
+								   (int) ProcDieSenderPid,
+								   (int) ProcDieSenderUid)));
+			else
+				ereport(WARNING,
+						(errcode(ERRCODE_ADMIN_SHUTDOWN),
+						 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
+						 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
 			whereToSendOutput = DestNone;
 			SyncRepCancelWait();
 			break;
diff --git a/src/backend/replication/walreceiver.c b/src/backend/replication/walreceiver.c
index 09fde92bfd7..6da5b86dbc5 100644
--- a/src/backend/replication/walreceiver.c
+++ b/src/backend/replication/walreceiver.c
@@ -248,16 +248,16 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 	/* Properly accept or ignore signals the postmaster might send us */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload); /* set flag to read config
 													 * file */
-	pqsignal(SIGINT, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
 	pqsignal(SIGTERM, die);		/* request shutdown */
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 
 	/* Reset some signals that are accepted by postmaster but not here */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/* Load the libpq-specific functions */
 	load_file("libpqwalreceiver", false);
diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c
index bad45adb004..3d4ab929f91 100644
--- a/src/backend/replication/walsender.c
+++ b/src/backend/replication/walsender.c
@@ -3897,13 +3897,13 @@ WalSndSignals(void)
 	pqsignal(SIGTERM, die);		/* request shutdown */
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
 	InitializeTimeouts();		/* establishes SIGALRM handler */
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, WalSndLastCycleHandler);	/* request a last cycle and
 												 * shutdown */
 
 	/* Reset some signals that are accepted by postmaster but not here */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 }
 
 /* Register shared-memory space needed by walsender */
diff --git a/src/backend/storage/aio/method_worker.c b/src/backend/storage/aio/method_worker.c
index a5ccd506d8c..061a93d90d4 100644
--- a/src/backend/storage/aio/method_worker.c
+++ b/src/backend/storage/aio/method_worker.c
@@ -684,10 +684,10 @@ IoWorkerMain(const void *startup_data, size_t startup_data_len)
 	 * Ignore SIGTERM, will get explicit shutdown via SIGUSR2 later in the
 	 * shutdown sequence, similar to checkpointer.
 	 */
-	pqsignal(SIGTERM, SIG_IGN);
+	pqsignal(SIGTERM, PG_SIG_IGN);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, SignalHandlerForShutdownRequest);
 
diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c
index 01f1bd6e687..a8be066afe0 100644
--- a/src/backend/storage/file/fd.c
+++ b/src/backend/storage/file/fd.c
@@ -2748,11 +2748,11 @@ OpenPipeStream(const char *command, const char *mode)
 
 TryAgain:
 	fflush(NULL);
-	pqsignal(SIGPIPE, SIG_DFL);
+	pqsignal(SIGPIPE, PG_SIG_DFL);
 	errno = 0;
 	file = popen(command, mode);
 	save_errno = errno;
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	errno = save_errno;
 	if (file != NULL)
 	{
diff --git a/src/backend/storage/ipc/waiteventset.c b/src/backend/storage/ipc/waiteventset.c
index 0f228e1e7b8..627dba0a842 100644
--- a/src/backend/storage/ipc/waiteventset.c
+++ b/src/backend/storage/ipc/waiteventset.c
@@ -348,7 +348,7 @@ InitializeWaitEventSupport(void)
 
 #ifdef WAIT_USE_KQUEUE
 	/* Ignore SIGURG, because we'll receive it via kqueue. */
-	pqsignal(SIGURG, SIG_IGN);
+	pqsignal(SIGURG, PG_SIG_IGN);
 #endif
 }
 
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index aeaf1c6db8f..2c1f14b7889 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -3027,6 +3027,17 @@ die(SIGNAL_ARGS)
 	{
 		InterruptPending = true;
 		ProcDiePending = true;
+
+		/*
+		 * Record who sent the signal.  Will be 0 on platforms without
+		 * SA_SIGINFO, which is fine -- ProcessInterrupts() checks for that.
+		 * Only set on the first SIGTERM so we report the original sender.
+		 */
+		if (ProcDieSenderPid == 0)
+		{
+			ProcDieSenderPid = pg_siginfo->pid;
+			ProcDieSenderUid = pg_siginfo->uid;
+		}
 	}
 
 	/* for the cumulative stats system */
@@ -4316,17 +4327,17 @@ PostgresMain(const char *dbname, const char *username)
 		 * returns to outer loop.  This seems safer than forcing exit in the
 		 * midst of output during who-knows-what operation...
 		 */
-		pqsignal(SIGPIPE, SIG_IGN);
+		pqsignal(SIGPIPE, PG_SIG_IGN);
 		pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-		pqsignal(SIGUSR2, SIG_IGN);
+		pqsignal(SIGUSR2, PG_SIG_IGN);
 		pqsignal(SIGFPE, FloatExceptionHandler);
 
 		/*
 		 * Reset some signals that are accepted by postmaster but not by
 		 * backend
 		 */
-		pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
-									 * platforms */
+		pqsignal(SIGCHLD, PG_SIG_DFL);	/* system() requires this on some
+										 * platforms */
 	}
 
 	/* Early initialization */
diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index 509f1114ef6..44a2c7a7c7f 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -2903,10 +2903,10 @@ setup_signals(void)
 	pqsignal(SIGQUIT, trapsig);
 
 	/* Ignore SIGPIPE when writing to backend, so we can clean up */
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 
 	/* Prevent SIGSYS so we can probe for kernel calls that might not work */
-	pqsignal(SIGSYS, SIG_IGN);
+	pqsignal(SIGSYS, PG_SIG_IGN);
 #endif
 }
 
diff --git a/src/bin/pg_ctl/pg_ctl.c b/src/bin/pg_ctl/pg_ctl.c
index 3cc61455dcb..5539eb8ebef 100644
--- a/src/bin/pg_ctl/pg_ctl.c
+++ b/src/bin/pg_ctl/pg_ctl.c
@@ -868,7 +868,7 @@ trap_sigint_during_startup(SIGNAL_ARGS)
 	 * Clear the signal handler, and send the signal again, to terminate the
 	 * process as normal.
 	 */
-	pqsignal(postgres_signal_arg, SIG_DFL);
+	pqsignal(postgres_signal_arg, PG_SIG_DFL);
 	raise(postgres_signal_arg);
 }
 
diff --git a/src/bin/pg_dump/parallel.c b/src/bin/pg_dump/parallel.c
index a28561fbd84..a7bed5ecccf 100644
--- a/src/bin/pg_dump/parallel.c
+++ b/src/bin/pg_dump/parallel.c
@@ -568,9 +568,9 @@ sigTermHandler(SIGNAL_ARGS)
 	 * signal handler.  That could muck up our attempt to send PQcancel, so
 	 * disable the signals that set_cancel_handler enabled.
 	 */
-	pqsignal(SIGINT, SIG_IGN);
-	pqsignal(SIGTERM, SIG_IGN);
-	pqsignal(SIGQUIT, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
+	pqsignal(SIGTERM, PG_SIG_IGN);
+	pqsignal(SIGQUIT, PG_SIG_IGN);
 
 	/*
 	 * If we're in the leader, forward signal to all workers.  (It seems best
@@ -1049,7 +1049,7 @@ ParallelBackupStart(ArchiveHandle *AH)
 	 * the workers to inherit this setting, though.
 	 */
 #ifndef WIN32
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 #endif
 
 	/*
diff --git a/src/bin/psql/t/001_basic.pl b/src/bin/psql/t/001_basic.pl
index 7c21204c1f2..9d966c7bece 100644
--- a/src/bin/psql/t/001_basic.pl
+++ b/src/bin/psql/t/001_basic.pl
@@ -142,8 +142,11 @@ my ($ret, $out, $err) = $node->psql('postgres',
 is($ret, 2, 'server crash: psql exit code');
 like($out, qr/before/, 'server crash: output before crash');
 unlike($out, qr/AFTER/, 'server crash: no output after crash');
+my $detail_re = check_pg_config("#define HAVE_SA_SIGINFO 1")
+	? qr/DETAIL:  Signal sent by PID \d+, UID \d+\.\n/
+	: qr//;
 like( $err, qr/psql:<stdin>:2: FATAL:  terminating connection due to administrator command
-(?:DETAIL:  Signal sent by PID \d+, UID \d+\.\n)?psql:<stdin>:2: server closed the connection unexpectedly
+${detail_re}psql:<stdin>:2: server closed the connection unexpectedly
 	This probably means the server terminated abnormally
 	before or while processing the request.
 psql:<stdin>:2: error: connection to server was lost/,
diff --git a/src/fe_utils/print.c b/src/fe_utils/print.c
index 12d969e8666..f2dd52003c1 100644
--- a/src/fe_utils/print.c
+++ b/src/fe_utils/print.c
@@ -3024,7 +3024,7 @@ void
 disable_sigpipe_trap(void)
 {
 #ifndef WIN32
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 #endif
 }
 
@@ -3047,7 +3047,7 @@ void
 restore_sigpipe_trap(void)
 {
 #ifndef WIN32
-	pqsignal(SIGPIPE, always_ignore_sigpipe ? SIG_IGN : SIG_DFL);
+	pqsignal(SIGPIPE, always_ignore_sigpipe ? PG_SIG_IGN : PG_SIG_DFL);
 #endif
 }
 
diff --git a/src/include/c.h b/src/include/c.h
index 88d13ec9993..77ea73cc707 100644
--- a/src/include/c.h
+++ b/src/include/c.h
@@ -1441,17 +1441,26 @@ extern int	fdatasync(int fd);
 #endif
 
 /*
- * The following is used as the arg list for signal handlers.  Any ports
- * that take something other than an int argument should override this in
- * their pg_config_os.h file.  Note that variable names are required
- * because it is used in both the prototypes as well as the definitions.
- * Note also the long name.  We expect that this won't collide with
- * other names causing compiler warnings.
+ * Platform independent struct representing additional information about the
+ * received signal.  If the system does not support the extended information,
+ * or a field does not apply to the signal, the value is instead reset to the
+ * documented default value.
  */
+typedef struct pg_signal_info
+{
+	pid_t		pid;			/* pid of sending process or 0 if unknown */
+	uid_t		uid;			/* uid of sending process or 0 if unknown */
+} pg_signal_info;
 
-#ifndef SIGNAL_ARGS
-#define SIGNAL_ARGS  int postgres_signal_arg
-#endif
+/*
+ * The following is used as the arg list for signal handlers. These days we
+ * use the same argument to all signal handlers and hide the difference
+ * between platforms in wrapper functions.
+ *
+ * SIGNAL_ARGS just exists separately from the pqsignal() definition for
+ * historical reasons.
+ */
+#define SIGNAL_ARGS  int postgres_signal_arg, pg_signal_info *pg_siginfo
 
 /*
  * When there is no sigsetjmp, its functionality is provided by plain
diff --git a/src/include/port.h b/src/include/port.h
index 51df9b80e7d..7db476d7b01 100644
--- a/src/include/port.h
+++ b/src/include/port.h
@@ -546,6 +546,9 @@ extern int	pg_mkdir_p(char *path, int omode);
 #else
 #define pqsignal pqsignal_be
 #endif
+
+#define PG_SIG_DFL (pqsigfunc) SIG_DFL
+#define PG_SIG_IGN (pqsigfunc) SIG_IGN
 typedef void (*pqsigfunc) (SIGNAL_ARGS);
 extern void pqsignal(int signo, pqsigfunc func);
 
diff --git a/src/interfaces/libpq/legacy-pqsignal.c b/src/interfaces/libpq/legacy-pqsignal.c
index 1285b033e1b..0735e4ee0d5 100644
--- a/src/interfaces/libpq/legacy-pqsignal.c
+++ b/src/interfaces/libpq/legacy-pqsignal.c
@@ -36,10 +36,12 @@
  * is to ensure that no in-tree code accidentally calls this version.)
  */
 #undef pqsignal
-extern pqsigfunc pqsignal(int signo, pqsigfunc func);
 
-pqsigfunc
-pqsignal(int signo, pqsigfunc func)
+typedef void (*pqsigfunc_legacy) (int postgres_signal_arg);
+extern pqsigfunc_legacy pqsignal(int signo, pqsigfunc_legacy func);
+
+pqsigfunc_legacy
+pqsignal(int signo, pqsigfunc_legacy func)
 {
 #ifndef WIN32
 	struct sigaction act,
diff --git a/src/port/pqsignal.c b/src/port/pqsignal.c
index 8841464b5cb..2b39be99f94 100644
--- a/src/port/pqsignal.c
+++ b/src/port/pqsignal.c
@@ -63,6 +63,14 @@
 #define PG_NSIG (64)			/* XXX: wild guess */
 #endif
 
+#if !(defined(WIN32) && defined(FRONTEND))
+#define USE_SIGACTION
+#endif
+
+#if defined(USE_SIGACTION) && defined(HAVE_SA_SIGINFO)
+#define USE_SIGINFO
+#endif
+
 /* Check a couple of common signals to make sure PG_NSIG is accurate. */
 StaticAssertDecl(SIGUSR2 < PG_NSIG, "SIGUSR2 >= PG_NSIG");
 StaticAssertDecl(SIGHUP < PG_NSIG, "SIGHUP >= PG_NSIG");
@@ -82,19 +90,16 @@ static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
  *
  * This wrapper also handles restoring the value of errno.
  */
-#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+#ifdef USE_SIGACTION
 static void
-wrapper_handler(int signo, siginfo_t * info, void *context)
+wrapper_handler(int postgres_signal_arg, siginfo_t *info, void *context)
 #else
 static void
-wrapper_handler(SIGNAL_ARGS)
+wrapper_handler(int postgres_signal_arg)
 #endif
 {
 	int			save_errno = errno;
-#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
-	/* SA_SIGINFO signature uses signo, not SIGNAL_ARGS macro */
-	int			postgres_signal_arg = signo;
-#endif
+	pg_signal_info pg_info;
 
 	Assert(postgres_signal_arg > 0);
 	Assert(postgres_signal_arg < PG_NSIG);
@@ -110,21 +115,32 @@ wrapper_handler(SIGNAL_ARGS)
 
 	if (unlikely(MyProcPid != (int) getpid()))
 	{
-		pqsignal(postgres_signal_arg, SIG_DFL);
+		pqsignal(postgres_signal_arg, PG_SIG_DFL);
 		raise(postgres_signal_arg);
 		return;
 	}
+#endif
 
 #ifdef HAVE_SA_SIGINFO
-	if (signo == SIGTERM && info)
-	{
-		ProcDieSenderPid = info->si_pid;
-		ProcDieSenderUid = info->si_uid;
-	}
-#endif
+
+	/*
+	 * If supported by the system, forward interesting information from the
+	 * system's extended signal information to our platform independent
+	 * format.
+	 */
+	pg_info.pid = info->si_pid;
+	pg_info.uid = info->si_uid;
+#else
+
+	/*
+	 * Otherwise forward values indicating that we do not have the
+	 * information.
+	 */
+	pg_info.pid = 0;
+	pg_info.uid = 0;
 #endif
 
-	(*pqsignal_handlers[postgres_signal_arg]) (postgres_signal_arg);
+	(*pqsignal_handlers[postgres_signal_arg]) (postgres_signal_arg, &pg_info);
 
 	errno = save_errno;
 }
@@ -139,33 +155,44 @@ wrapper_handler(SIGNAL_ARGS)
 void
 pqsignal(int signo, pqsigfunc func)
 {
-#if !(defined(WIN32) && defined(FRONTEND))
+#ifdef USE_SIGACTION
 	struct sigaction act;
 #endif
-	bool		use_wrapper = false;
+	bool		is_ign = func == PG_SIG_IGN;
+	bool		is_dfl = func == PG_SIG_DFL;
 
 	Assert(signo > 0);
 	Assert(signo < PG_NSIG);
 
-	if (func != SIG_IGN && func != SIG_DFL)
+	/* set up indirection handler */
+	if (!(is_ign || is_dfl))
 	{
 		pqsignal_handlers[signo] = func;	/* assumed atomic */
-		use_wrapper = true;
 	}
 
-#if !(defined(WIN32) && defined(FRONTEND))
+	/*
+	 * Configure system to either ignore/reset the signal handler, or to
+	 * forward it to wrapper_handler.
+	 */
+#ifdef USE_SIGACTION
 	sigemptyset(&act.sa_mask);
 	act.sa_flags = SA_RESTART;
-#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
-	if (use_wrapper)
+
+	if (is_ign)
+		act.sa_handler = SIG_IGN;
+	else if (is_dfl)
+		act.sa_handler = SIG_DFL;
+
+#ifdef USE_SIGINFO
+	if (!(is_ign || is_dfl))
 	{
 		act.sa_sigaction = wrapper_handler;
 		act.sa_flags |= SA_SIGINFO;
 	}
 	else
-		act.sa_handler = func;
 #else
-	act.sa_handler = use_wrapper ? wrapper_handler : func;
+	else
+		act.sa_handler = wrapper_handler;
 #endif
 
 #ifdef SA_NOCLDSTOP
diff --git a/src/test/regress/pg_regress.c b/src/test/regress/pg_regress.c
index 0c062056982..c26efeba1ee 100644
--- a/src/test/regress/pg_regress.c
+++ b/src/test/regress/pg_regress.c
@@ -492,7 +492,7 @@ signal_remove_temp(SIGNAL_ARGS)
 {
 	remove_temp();
 
-	pqsignal(postgres_signal_arg, SIG_DFL);
+	pqsignal(postgres_signal_arg, PG_SIG_DFL);
 	raise(postgres_signal_arg);
 }
 
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index ea95e7984bc..49dfb662abc 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -4039,6 +4039,7 @@ pg_sha224_ctx
 pg_sha256_ctx
 pg_sha384_ctx
 pg_sha512_ctx
+pg_signal_info
 pg_snapshot
 pg_special_case
 pg_stack_base_t
-- 
2.43.0



^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-14 20:38  Andrew Dunstan <andrew@dunslane.net>
  parent: Jakub Wartak <jakub.wartak@enterprisedb.com>
  0 siblings, 2 replies; 54+ messages in thread

From: Andrew Dunstan @ 2026-04-14 20:38 UTC (permalink / raw)
  To: Jakub Wartak <jakub.wartak@enterprisedb.com>; Chao Li <li.evan.chao@gmail.com>; +Cc: Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>


On 2026-04-14 Tu 6:40 AM, Jakub Wartak wrote:
> Hi Andres, Andrew, Chao
>
> thanks for putting so much effort into enhancing the the previous implementation
> of this code. Earlier I was not aware of potential problems involved.
>
> On Fri, Apr 10, 2026 at 9:41 AM Chao Li <li.evan.chao@gmail.com> wrote:
>>
>>
>>> On Apr 9, 2026, at 18:59, Andrew Dunstan <andrew@dunslane.net> wrote:
>>>
>>>
>>> On 2026-04-08 We 1:01 PM, Andres Freund wrote:
>>>> Hi,
>>>>
>>>> Attached is a very rough first draft for how I think this needs to look like.
>>>>
>>>> Basically, SIGNAL_INFO always will pass both the signal number and extended
>>>> information along to the signal handler. The extended information is a
>>>> postgres specific struct. If the platform can't provide the extended
>>>> information, the values are instead set to some default value indicating that
>>>> the information is not known.
>>>>
>>>> With that die() (and also StatementCancelHandler, ...) can just set whatever
>>>> globals it wants, without pqsignal.c needing to know about it.
>>>>
>>>> It also allows us to extend the amount of information in the future. E.g. I'd
>>>> like to log the reason for a segfault (could e.g. be an OOM kill or an umapped
>>>> region) to stderr.
>>>>
>>>> The annoying thing about it is needing to change nearly all the existing
>>>> references to SIG_IGN/SIG_DFL, to avoid warnings due to mismatched types.
>>> I agree that's annoying. The only way around it I found was via some casting to/from void* that I suspect you would find a cure worse than the disease.
>>> I reworked your patch slightly. This version fixes the translatability issue you raised earlier, makes the TAP test from the original commit more robust, and  tries to resolve your XXX issue by moving the assignment of ProcDieSenderPid/Uid inside the "if (!proc_exit_inprogress)" block.
>>>
>> I reviewed this version. Besides the compile warning and uid 0 issues, I got a few more comments, so I try to put them all together as below.
>>
> TL;DR; win/mingw is really unhappy with the state of rework patch right now.
> I've tried to enhance and fix it, and now it's green for default CI run and
> also for mingw too. Attached 0002-fixup-win32 patch does not incorporate Chao's
> all findings so far.
>
> [..]
>> 2 - uid 0 problem
>> ```
>> +typedef struct pg_signal_info
>> +{
>> +       pid_t           pid;                    /* pid of sending process or 0 if unknown */
>> +       uid_t           uid;                    /* uid of sending process or 0 if unknown */
>> +} pg_signal_info;
>> ```
>>
>> I think we can mention that “uid” is only meaningful when pid is set.
> [..]
>> 5
>> ```
>> +       pg_info.uid = 0;
>> ```
>>
>> If you take comment 2, then when unavailable, we can just don’t assign anything to pg_info.uid. Or "(uid_t)-1", maybe.
>>
>
> I. I've started from this and I vaguley remembered that I had terrible
> experience
> when trying to chose the proper types for those field types, but I couldn't
> remind myself why, so I've gave a try of the current rework patch and got this
> on Windows Server 2022, vs2019, cirrus-ci said:
>
> [08:40:22.848] c:\cirrus\src\include\c.h(1451): error C2061: syntax
> error: identifier 'pid_t'
> [08:40:22.848] c:\cirrus\src\include\c.h(1452): error C2061: syntax
> error: identifier 'uid'
> [08:40:22.848] c:\cirrus\src\include\c.h(1452): error C2059: syntax error: ';'
> [08:40:22.848] c:\cirrus\src\include\c.h(1453): error C2059: syntax error: '}'
>
> for c.h:
>    1449  typedef struct pg_signal_info
>    1450  {
>    1451          pid_t           pid;                    /* pid of
> sending process or 0 if unknown */
>    1452          uid_t           uid;                    /* uid of
> sending process or 0 if unknown */
>    1453  } pg_signal_info;
>
> so maybe we should just move that typedef with SIGNAL_ARGS to after
> "include of port.h" (line ~1471) in that c.h, because only then we'll have
> access to:
>      src/include/port/win32_port.h:typedef int pid_t;
>      src/include/port/win32_port.h:typedef int uid_t;
> but the problem is that port.h itself requires SIGNAL_ARGS to be defined
> and that seems to be like chicken and egg problem.  I thought that just
> using native "ints" could be the way to go, but the problem is that now
> that uid_t can be bigger than pid_t as Linux kernel headers show this:
>
> x86_64-linux-gnu/bits/types.h:#define   __S32_TYPE              int
> x86_64-linux-gnu/bits/types.h:#define __U32_TYPE                unsigned int
> x86_64-linux-gnu/bits/types.h:__STD_TYPE __UID_T_TYPE __uid_t;  /*
> Type of user identifications.  */
> x86_64-linux-gnu/bits/types.h:__STD_TYPE __PID_T_TYPE __pid_t;  /*
> Type of process identifications.  */
> x86_64-linux-gnu/bits/typesizes.h:#define __UID_T_TYPE          __U32_TYPE
> x86_64-linux-gnu/bits/typesizes.h:#define __PID_T_TYPE          __S32_TYPE
>
> so maybe do that typedef struct pg_signal_info with 2x uint32_t and that's
> good enough? (it covers the ranges necessary and makes it platform compatible)
>
> II. While we are tthis so with above uid_t of up to being u32, possibly
> `volatile int ProcDieSenderUid/Pid` should be also bigger like uint32_t?
> My fixup-patch does not incude it, because I don't know really.
>
> III. As Chao said I've used:
>
> +#define PG_SIG_DFL (pqsigfunc) (pg_funcptr_t) SIG_DFL
> +#define PG_SIG_IGN (pqsigfunc) (pg_funcptr_t) SIG_IGN
>
> IV.  Then just got lots of warnings for use_wrapper/wrapp_handler and so on
>
> [09:27:33.602] ../src/port/pqsignal.c(206): error C2065:
> 'use_wrapper': undeclared identifier
> [09:27:33.602] ../src/port/pqsignal.c(206): warning C4113: 'pqsigfunc'
> differs in parameter lists from 'void (__cdecl *)(int)'
>
> that's for:
>     204  #else
>     205          /* Forward to Windows native signal system. */
>     206          if (signal(signo, use_wrapper ? wrapper_handler :
> func) == SIG_ERR)
>     207                  Assert(false);                  /* probably
> indicates coding error */
>
> In the end, I've ended up using wrapper_handler for the windows path there
> as signal() requires function with single param.
>
> IV. Got some further issues, and VC complained that siginfo_t is used for
> USE_SIGACTION - isn't it impossible on win32? Anyway, that makes some sense,
> USE_SIGINFO is not defined and we use 'siginfo_t', so something like fixes it:
>
> @@ -90,7 +90,7 @@ static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
>    *
>    * This wrapper also handles restoring the value of errno.
>    */
> -#ifdef USE_SIGACTION
> +#if defined(USE_SIGACTION) && defined(USE_SIGINFO)
>   static void
>   wrapper_handler(int postgres_signal_arg, siginfo_t *info, void *context)
>   #else
>
> V. Later I've stumbled on series of other problems related to
> src/backend/port/win32/signal.c (it also uses SIG_DFL but not PG_SIG_DFL and
> stil somewhat references pgsigfunc, so those changes seemed to impact it).
>
> Also there was:
> [10:37:02.824] ../src/backend/port/win32/signal.c(154): error C2198:
> 'sig': too few arguments for call
>
> so I've fixed with adding nodata struct there and:
> @@ -151,7 +154,7 @@ pgwin32_dispatch_queued_signals(void)
>                                                  block_mask |= sigmask(i);
>
>                                          sigprocmask(SIG_BLOCK,
> &block_mask, &save_mask);
> -                                       sig(i);
> +                                       sig(i, &nodata);
>                                          sigprocmask(SIG_SETMASK,
> &save_mask, NULL);
>
> VI. Possibly we could rename USE_SIGACTION define because at least to me it
> is confusing to me to reason and communicate about in terms of win32 context
> on win32 do we do have it or not? (it can be both ways):
> * win32 C API doesnt have it
> * PG does have sigaction win32 wrapper with override macro
>    #define sigaction.. pqsigaction..
> * however src/include/libpq/pqsignal.h says "sa_sigaction not yet implemented"
>    for it (so with USE_SIGACTION are we talking about sa_sigaction field memeber
>    that it's not used or about sigaction function?)
>
> VII. FWIW, I've also removed superflous "else"
>   #ifdef USE_SIGINFO
>          if (!(is_ign || is_dfl))
>          {
>                  act.sa_sigaction = wrapper_handler;
>                  act.sa_flags |= SA_SIGINFO;
>          }
> -       else
>   #else
>
>


I'm not 100% sure that else shouldn't be there. Maybe have another look?

Attached is a consolidation that includes your other fixes, plus:

. uid comment -- "only meaningful when pid is not 0"
. const pg_signal_info *pg_siginfo in SIGNAL_ARGS
. 2 spaces after period in syncrep.c errdetail


cheers


andrew



--
Andrew Dunstan
EDB: https://www.enterprisedb.com

Attachments:

  [text/x-patch] v2-0001-Rework-signal-handler-infrastructure-to-pass-send.patch (37.0K, ../../833f045b-286a-45dc-aad1-28854cbacc99@dunslane.net/2-v2-0001-Rework-signal-handler-infrastructure-to-pass-send.patch)
  download | inline diff:
From 9a3c4a1c005b254263a3ff3d8b8ee4cf2f0e5764 Mon Sep 17 00:00:00 2001
From: Andrew Dunstan <andrew@dunslane.net>
Date: Tue, 14 Apr 2026 16:13:08 -0400
Subject: [PATCH v2] Rework signal handler infrastructure to pass sender info
 as argument.

Commit 095c9d4cf06 added errdetail() reporting of the PID and UID of
the process that sent a termination signal.  However, as noted by
Andres Freund, the implementation had architectural problems:

1. wrapper_handler() in pqsignal.c contained SIGTERM-specific logic
   (setting ProcDieSenderPid/Uid), violating its role as a generic
   signal dispatch wrapper.

2. Using globals to pass sender info between wrapper_handler and the
   real handler is unsafe when signals nest on some platforms.

3. The syncrep.c errdetail used psprintf() to conditionally embed
   text via %s, breaking translatability.

Adopt the approach proposed by Andres Freund: introduce a
pg_signal_info struct that is passed as an argument to all signal
handlers via the SIGNAL_ARGS macro.  wrapper_handler populates it
from siginfo_t when SA_SIGINFO is available, or with zeros otherwise.
This keeps wrapper_handler fully generic and avoids any globals for
passing signal metadata.

Since pqsigfunc now has a different signature from the system's
signal handler type, SIG_IGN and SIG_DFL can no longer be passed
directly to pqsignal().  Introduce PG_SIG_IGN and PG_SIG_DFL macros
that cast to the new pqsigfunc type, and update all call sites.
The legacy pqsignal() in libpq retains its original signature via
a local typedef.

Only die() reads pg_siginfo today, copying the sender PID/UID into
ProcDieSenderPid/Uid for later use by ProcessInterrupts().  Only the
first SIGTERM's sender info is recorded.

Also fix the syncrep.c translatability issue by using separate ereport
calls with complete, independently translatable errdetail strings.

Also make the psql TAP test require the DETAIL line on platforms with
SA_SIGINFO, rather than making it unconditionally optional.

On Windows, pg_signal_info uses uint32_t for pid and uid fields
since pid_t/uid_t are not available early enough in the include
chain.  The Windows signal dispatch in pgwin32_dispatch_queued_signals()
passes a zeroed pg_signal_info to handlers.

Author: Andres Freund <andres@anarazel.de>
Author: Jakub Wartak <jakub.wartak@enterprisedb.com>
Reviewed-by: Andrew Dunstan <andrew@dunslane.net>
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://postgr.es/m/cwyyryh2veejuxbj5ifzyaejw7jhhqc5mrdeq56xckknsdecn2@6hzfcxde2nm5
Discussion: https://postgr.es/m/jygesyr7mwg7ovdbxpmjvvbi3hccptpkcreqb645h7f56puwbz@hmkkwi3melfe
---
 src/backend/bootstrap/bootstrap.c           |  8 +-
 src/backend/port/win32/signal.c             | 13 +--
 src/backend/postmaster/autovacuum.c         | 10 +--
 src/backend/postmaster/bgworker.c           | 14 +--
 src/backend/postmaster/bgwriter.c           | 10 +--
 src/backend/postmaster/checkpointer.c       |  8 +-
 src/backend/postmaster/datachecksum_state.c |  2 +-
 src/backend/postmaster/pgarch.c             |  8 +-
 src/backend/postmaster/postmaster.c         | 12 +--
 src/backend/postmaster/startup.c            |  6 +-
 src/backend/postmaster/syslogger.c          | 14 +--
 src/backend/postmaster/walsummarizer.c      | 10 +--
 src/backend/postmaster/walwriter.c          | 10 +--
 src/backend/replication/logical/slotsync.c  |  6 +-
 src/backend/replication/syncrep.c           | 28 +++---
 src/backend/replication/walreceiver.c       | 10 +--
 src/backend/replication/walsender.c         |  4 +-
 src/backend/storage/aio/method_worker.c     |  6 +-
 src/backend/storage/file/fd.c               |  4 +-
 src/backend/storage/ipc/waiteventset.c      |  2 +-
 src/backend/tcop/postgres.c                 | 19 ++++-
 src/bin/initdb/initdb.c                     |  4 +-
 src/bin/pg_ctl/pg_ctl.c                     |  2 +-
 src/bin/pg_dump/parallel.c                  |  8 +-
 src/bin/psql/t/001_basic.pl                 |  5 +-
 src/fe_utils/print.c                        |  4 +-
 src/include/c.h                             | 29 +++++--
 src/include/port.h                          |  3 +
 src/interfaces/libpq/legacy-pqsignal.c      |  8 +-
 src/port/pqsignal.c                         | 95 ++++++++++++++-------
 src/test/regress/pg_regress.c               |  2 +-
 src/tools/pgindent/typedefs.list            |  1 +
 32 files changed, 216 insertions(+), 149 deletions(-)

diff --git a/src/backend/bootstrap/bootstrap.c b/src/backend/bootstrap/bootstrap.c
index 63378ab3d8c..b487289d4a3 100644
--- a/src/backend/bootstrap/bootstrap.c
+++ b/src/backend/bootstrap/bootstrap.c
@@ -463,10 +463,10 @@ bootstrap_signals(void)
 	 * mode; "curl up and die" is a sufficient response for all these cases.
 	 * Let's set that handling explicitly, as documentation if nothing else.
 	 */
-	pqsignal(SIGHUP, SIG_DFL);
-	pqsignal(SIGINT, SIG_DFL);
-	pqsignal(SIGTERM, SIG_DFL);
-	pqsignal(SIGQUIT, SIG_DFL);
+	pqsignal(SIGHUP, PG_SIG_DFL);
+	pqsignal(SIGINT, PG_SIG_DFL);
+	pqsignal(SIGTERM, PG_SIG_DFL);
+	pqsignal(SIGQUIT, PG_SIG_DFL);
 }
 
 /* ----------------------------------------------------------------
diff --git a/src/backend/port/win32/signal.c b/src/backend/port/win32/signal.c
index 465d69a1f28..d7cdb1cd1fe 100644
--- a/src/backend/port/win32/signal.c
+++ b/src/backend/port/win32/signal.c
@@ -88,7 +88,7 @@ pgwin32_signal_initialize(void)
 		pg_signal_array[i].sa_handler = SIG_DFL;
 		pg_signal_array[i].sa_mask = 0;
 		pg_signal_array[i].sa_flags = 0;
-		pg_signal_defaults[i] = SIG_IGN;
+		pg_signal_defaults[i] = PG_SIG_IGN;
 	}
 	pg_signal_mask = 0;
 	pg_signal_queue = 0;
@@ -134,15 +134,18 @@ pgwin32_dispatch_queued_signals(void)
 			{
 				/* Execute this signal */
 				struct sigaction *act = &pg_signal_array[i];
-				pqsigfunc	sig = act->sa_handler;
+				pqsigfunc	sig = (pqsigfunc)(pg_funcptr_t) act->sa_handler;
 
-				if (sig == SIG_DFL)
+				if (sig == PG_SIG_DFL)
 					sig = pg_signal_defaults[i];
 				pg_signal_queue &= ~sigmask(i);
-				if (sig != SIG_ERR && sig != SIG_IGN && sig != SIG_DFL)
+				if (sig != (pqsigfunc)(pg_funcptr_t)SIG_ERR && sig != PG_SIG_IGN && sig != PG_SIG_DFL)
 				{
 					sigset_t	block_mask;
 					sigset_t	save_mask;
+					struct pg_signal_info nodata;
+					nodata.pid = 0;
+					nodata.uid = 0;
 
 					LeaveCriticalSection(&pg_signal_crit_sec);
 
@@ -151,7 +154,7 @@ pgwin32_dispatch_queued_signals(void)
 						block_mask |= sigmask(i);
 
 					sigprocmask(SIG_BLOCK, &block_mask, &save_mask);
-					sig(i);
+					sig(i, &nodata);
 					sigprocmask(SIG_SETMASK, &save_mask, NULL);
 
 					EnterCriticalSection(&pg_signal_crit_sec);
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index c4d6b8811bf..9fedf68c6af 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -448,11 +448,11 @@ AutoVacLauncherMain(const void *startup_data, size_t startup_data_len)
 
 	InitializeTimeouts();		/* establishes SIGALRM handler */
 
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, avl_sigusr2_handler);
 	pqsignal(SIGFPE, FloatExceptionHandler);
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Create a per-backend PGPROC struct in shared memory.  We must do this
@@ -1459,11 +1459,11 @@ AutoVacWorkerMain(const void *startup_data, size_t startup_data_len)
 
 	InitializeTimeouts();		/* establishes SIGALRM handler */
 
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 	pqsignal(SIGFPE, FloatExceptionHandler);
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Create a per-backend PGPROC struct in shared memory.  We must do this
diff --git a/src/backend/postmaster/bgworker.c b/src/backend/postmaster/bgworker.c
index 0992b9b6353..4569d9d232f 100644
--- a/src/backend/postmaster/bgworker.c
+++ b/src/backend/postmaster/bgworker.c
@@ -780,19 +780,19 @@ BackgroundWorkerMain(const void *startup_data, size_t startup_data_len)
 	}
 	else
 	{
-		pqsignal(SIGINT, SIG_IGN);
-		pqsignal(SIGUSR1, SIG_IGN);
-		pqsignal(SIGFPE, SIG_IGN);
+		pqsignal(SIGINT, PG_SIG_IGN);
+		pqsignal(SIGUSR1, PG_SIG_IGN);
+		pqsignal(SIGFPE, PG_SIG_IGN);
 	}
 	pqsignal(SIGTERM, die);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGHUP, SIG_IGN);
+	pqsignal(SIGHUP, PG_SIG_IGN);
 
 	InitializeTimeouts();		/* establishes SIGALRM handler */
 
-	pqsignal(SIGPIPE, SIG_IGN);
-	pqsignal(SIGUSR2, SIG_IGN);
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * If an exception is encountered, processing resumes here.
diff --git a/src/backend/postmaster/bgwriter.c b/src/backend/postmaster/bgwriter.c
index 1d8947774a9..d364382303a 100644
--- a/src/backend/postmaster/bgwriter.c
+++ b/src/backend/postmaster/bgwriter.c
@@ -101,18 +101,18 @@ BackgroundWriterMain(const void *startup_data, size_t startup_data_len)
 	 * Properly accept or ignore signals that might be sent to us.
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
-	pqsignal(SIGINT, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
 	pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * We just started, assume there has been either a shutdown or
diff --git a/src/backend/postmaster/checkpointer.c b/src/backend/postmaster/checkpointer.c
index 6b424ee610f..087120db090 100644
--- a/src/backend/postmaster/checkpointer.c
+++ b/src/backend/postmaster/checkpointer.c
@@ -223,17 +223,17 @@ CheckpointerMain(const void *startup_data, size_t startup_data_len)
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
 	pqsignal(SIGINT, ReqShutdownXLOG);
-	pqsignal(SIGTERM, SIG_IGN); /* ignore SIGTERM */
+	pqsignal(SIGTERM, PG_SIG_IGN);	/* ignore SIGTERM */
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, SignalHandlerForShutdownRequest);
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Initialize so that first time-driven event happens at the correct time.
diff --git a/src/backend/postmaster/datachecksum_state.c b/src/backend/postmaster/datachecksum_state.c
index 1243949eacb..18797a8ee3d 100644
--- a/src/backend/postmaster/datachecksum_state.c
+++ b/src/backend/postmaster/datachecksum_state.c
@@ -1020,7 +1020,7 @@ DataChecksumsWorkerLauncherMain(Datum arg)
 	pqsignal(SIGTERM, die);
 	pqsignal(SIGINT, launcher_cancel_handler);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 
 	BackgroundWorkerUnblockSignals();
 
diff --git a/src/backend/postmaster/pgarch.c b/src/backend/postmaster/pgarch.c
index 0a1a1149d78..0f207ac0356 100644
--- a/src/backend/postmaster/pgarch.c
+++ b/src/backend/postmaster/pgarch.c
@@ -229,16 +229,16 @@ PgArchiverMain(const void *startup_data, size_t startup_data_len)
 	 * except for SIGHUP, SIGTERM, SIGUSR1, SIGUSR2, and SIGQUIT.
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
-	pqsignal(SIGINT, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
 	pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, pgarch_waken_stop);
 
 	/* Reset some signals that are accepted by postmaster but not here */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/* Unblock signals (they were blocked when the postmaster forked us) */
 	sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
index 6f13e8f40a0..0a9b336d650 100644
--- a/src/backend/postmaster/postmaster.c
+++ b/src/backend/postmaster/postmaster.c
@@ -553,8 +553,8 @@ PostmasterMain(int argc, char *argv[])
 	pqsignal(SIGINT, handle_pm_shutdown_request_signal);
 	pqsignal(SIGQUIT, handle_pm_shutdown_request_signal);
 	pqsignal(SIGTERM, handle_pm_shutdown_request_signal);
-	pqsignal(SIGALRM, SIG_IGN); /* ignored */
-	pqsignal(SIGPIPE, SIG_IGN); /* ignored */
+	pqsignal(SIGALRM, PG_SIG_IGN);	/* ignored */
+	pqsignal(SIGPIPE, PG_SIG_IGN);	/* ignored */
 	pqsignal(SIGUSR1, handle_pm_pmsignal_signal);
 	pqsignal(SIGUSR2, dummy_handler);	/* unused, reserve for children */
 	pqsignal(SIGCHLD, handle_pm_child_exit_signal);
@@ -571,15 +571,15 @@ PostmasterMain(int argc, char *argv[])
 	 * child processes should just allow the inherited settings to stand.
 	 */
 #ifdef SIGTTIN
-	pqsignal(SIGTTIN, SIG_IGN); /* ignored */
+	pqsignal(SIGTTIN, PG_SIG_IGN);	/* ignored */
 #endif
 #ifdef SIGTTOU
-	pqsignal(SIGTTOU, SIG_IGN); /* ignored */
+	pqsignal(SIGTTOU, PG_SIG_IGN);	/* ignored */
 #endif
 
 	/* ignore SIGXFSZ, so that ulimit violations work like disk full */
 #ifdef SIGXFSZ
-	pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
+	pqsignal(SIGXFSZ, PG_SIG_IGN);	/* ignored */
 #endif
 
 	/* Begin accepting signals. */
@@ -3939,7 +3939,7 @@ process_pm_pmsignal(void)
  * Dummy signal handler
  *
  * We use this for signals that we don't actually use in the postmaster,
- * but we do use in backends.  If we were to SIG_IGN such signals in the
+ * but we do use in backends.  If we were to PG_SIG_IGN such signals in the
  * postmaster, then a newly started backend might drop a signal that arrives
  * before it's able to reconfigure its signal processing.  (See notes in
  * tcop/postgres.c.)
diff --git a/src/backend/postmaster/startup.c b/src/backend/postmaster/startup.c
index cdbe53dd262..b46bac681fe 100644
--- a/src/backend/postmaster/startup.c
+++ b/src/backend/postmaster/startup.c
@@ -226,18 +226,18 @@ StartupProcessMain(const void *startup_data, size_t startup_data_len)
 	 * Properly accept or ignore signals the postmaster might send us.
 	 */
 	pqsignal(SIGHUP, StartupProcSigHupHandler); /* reload config file */
-	pqsignal(SIGINT, SIG_IGN);	/* ignore query cancel */
+	pqsignal(SIGINT, PG_SIG_IGN);	/* ignore query cancel */
 	pqsignal(SIGTERM, StartupProcShutdownHandler);	/* request shutdown */
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
 	InitializeTimeouts();		/* establishes SIGALRM handler */
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, StartupProcTriggerHandler);
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Register timeouts needed for standby mode
diff --git a/src/backend/postmaster/syslogger.c b/src/backend/postmaster/syslogger.c
index 0c2a7bc8578..acfe0a01715 100644
--- a/src/backend/postmaster/syslogger.c
+++ b/src/backend/postmaster/syslogger.c
@@ -276,18 +276,18 @@ SysLoggerMain(const void *startup_data, size_t startup_data_len)
 
 	pqsignal(SIGHUP, SignalHandlerForConfigReload); /* set flag to read config
 													 * file */
-	pqsignal(SIGINT, SIG_IGN);
-	pqsignal(SIGTERM, SIG_IGN);
-	pqsignal(SIGQUIT, SIG_IGN);
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
+	pqsignal(SIGTERM, PG_SIG_IGN);
+	pqsignal(SIGQUIT, PG_SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, sigUsr1Handler);	/* request log rotation */
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
 
diff --git a/src/backend/postmaster/walsummarizer.c b/src/backend/postmaster/walsummarizer.c
index 20960f5b633..4f12eaf2c85 100644
--- a/src/backend/postmaster/walsummarizer.c
+++ b/src/backend/postmaster/walsummarizer.c
@@ -244,13 +244,13 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len)
 	 * Properly accept or ignore signals the postmaster might send us
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
-	pqsignal(SIGINT, SIG_IGN);	/* no query to cancel */
+	pqsignal(SIGINT, PG_SIG_IGN);	/* no query to cancel */
 	pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN); /* not used */
+	pqsignal(SIGUSR2, PG_SIG_IGN);	/* not used */
 
 	/* Advertise ourselves. */
 	on_shmem_exit(WalSummarizerShutdown, (Datum) 0);
@@ -267,7 +267,7 @@ WalSummarizerMain(const void *startup_data, size_t startup_data_len)
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * If an exception is encountered, processing resumes here.
diff --git a/src/backend/postmaster/walwriter.c b/src/backend/postmaster/walwriter.c
index 9cd86ad7022..af24d05c542 100644
--- a/src/backend/postmaster/walwriter.c
+++ b/src/backend/postmaster/walwriter.c
@@ -101,18 +101,18 @@ WalWriterMain(const void *startup_data, size_t startup_data_len)
 	 * Properly accept or ignore signals the postmaster might send us
 	 */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload);
-	pqsignal(SIGINT, SIG_IGN);	/* no query to cancel */
+	pqsignal(SIGINT, PG_SIG_IGN);	/* no query to cancel */
 	pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN); /* not used */
+	pqsignal(SIGUSR2, PG_SIG_IGN);	/* not used */
 
 	/*
 	 * Reset some signals that are accepted by postmaster but not here
 	 */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/*
 	 * Create a memory context that we will do all our work in.  We do this so
diff --git a/src/backend/replication/logical/slotsync.c b/src/backend/replication/logical/slotsync.c
index 8b53bd3ac7f..01607244bff 100644
--- a/src/backend/replication/logical/slotsync.c
+++ b/src/backend/replication/logical/slotsync.c
@@ -1555,9 +1555,9 @@ ReplSlotSyncWorkerMain(const void *startup_data, size_t startup_data_len)
 	pqsignal(SIGTERM, die);
 	pqsignal(SIGFPE, FloatExceptionHandler);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	check_and_set_sync_info(MyProcPid);
 
diff --git a/src/backend/replication/syncrep.c b/src/backend/replication/syncrep.c
index 46a778f0917..73450fe437e 100644
--- a/src/backend/replication/syncrep.c
+++ b/src/backend/replication/syncrep.c
@@ -300,22 +300,18 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 		 */
 		if (ProcDiePending)
 		{
-			/*
-			 * ProcDieSenderPid/Uid are read directly from the globals here
-			 * rather than copied to locals first; a second SIGTERM could
-			 * change them between reads, but that is harmless because the
-			 * process is about to die anyway.  The signal sender detail is
-			 * inlined rather than using a separate errdetail() call because
-			 * it must be appended to the existing detail message.
-			 */
-			ereport(WARNING,
-					(errcode(ERRCODE_ADMIN_SHUTDOWN),
-					 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
-					 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.%s",
-							   ProcDieSenderPid == 0 ? "" :
-							   psprintf("\nSignal sent by PID %d, UID %d.",
-										(int) ProcDieSenderPid,
-										(int) ProcDieSenderUid))));
+			if (ProcDieSenderPid != 0)
+				ereport(WARNING,
+						(errcode(ERRCODE_ADMIN_SHUTDOWN),
+						 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
+						 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.  Signal sent by PID %d, UID %d.",
+								   (int) ProcDieSenderPid,
+								   (int) ProcDieSenderUid)));
+			else
+				ereport(WARNING,
+						(errcode(ERRCODE_ADMIN_SHUTDOWN),
+						 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
+						 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.")));
 			whereToSendOutput = DestNone;
 			SyncRepCancelWait();
 			break;
diff --git a/src/backend/replication/walreceiver.c b/src/backend/replication/walreceiver.c
index a437273cf9a..9ad8b6648e6 100644
--- a/src/backend/replication/walreceiver.c
+++ b/src/backend/replication/walreceiver.c
@@ -250,16 +250,16 @@ WalReceiverMain(const void *startup_data, size_t startup_data_len)
 	/* Properly accept or ignore signals the postmaster might send us */
 	pqsignal(SIGHUP, SignalHandlerForConfigReload); /* set flag to read config
 													 * file */
-	pqsignal(SIGINT, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
 	pqsignal(SIGTERM, die);		/* request shutdown */
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-	pqsignal(SIGUSR2, SIG_IGN);
+	pqsignal(SIGUSR2, PG_SIG_IGN);
 
 	/* Reset some signals that are accepted by postmaster but not here */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 
 	/* Load the libpq-specific functions */
 	load_file("libpqwalreceiver", false);
diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c
index b4a2117a7f9..3957213a057 100644
--- a/src/backend/replication/walsender.c
+++ b/src/backend/replication/walsender.c
@@ -3896,13 +3896,13 @@ WalSndSignals(void)
 	pqsignal(SIGTERM, die);		/* request shutdown */
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
 	InitializeTimeouts();		/* establishes SIGALRM handler */
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, WalSndLastCycleHandler);	/* request a last cycle and
 												 * shutdown */
 
 	/* Reset some signals that are accepted by postmaster but not here */
-	pqsignal(SIGCHLD, SIG_DFL);
+	pqsignal(SIGCHLD, PG_SIG_DFL);
 }
 
 /* Register shared-memory space needed by walsender */
diff --git a/src/backend/storage/aio/method_worker.c b/src/backend/storage/aio/method_worker.c
index eb686cede1a..ca24af126e7 100644
--- a/src/backend/storage/aio/method_worker.c
+++ b/src/backend/storage/aio/method_worker.c
@@ -382,10 +382,10 @@ IoWorkerMain(const void *startup_data, size_t startup_data_len)
 	 * Ignore SIGTERM, will get explicit shutdown via SIGUSR2 later in the
 	 * shutdown sequence, similar to checkpointer.
 	 */
-	pqsignal(SIGTERM, SIG_IGN);
+	pqsignal(SIGTERM, PG_SIG_IGN);
 	/* SIGQUIT handler was already set up by InitPostmasterChild */
-	pqsignal(SIGALRM, SIG_IGN);
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGALRM, PG_SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
 	pqsignal(SIGUSR2, SignalHandlerForShutdownRequest);
 
diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c
index 01f1bd6e687..a8be066afe0 100644
--- a/src/backend/storage/file/fd.c
+++ b/src/backend/storage/file/fd.c
@@ -2748,11 +2748,11 @@ OpenPipeStream(const char *command, const char *mode)
 
 TryAgain:
 	fflush(NULL);
-	pqsignal(SIGPIPE, SIG_DFL);
+	pqsignal(SIGPIPE, PG_SIG_DFL);
 	errno = 0;
 	file = popen(command, mode);
 	save_errno = errno;
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 	errno = save_errno;
 	if (file != NULL)
 	{
diff --git a/src/backend/storage/ipc/waiteventset.c b/src/backend/storage/ipc/waiteventset.c
index 0f228e1e7b8..627dba0a842 100644
--- a/src/backend/storage/ipc/waiteventset.c
+++ b/src/backend/storage/ipc/waiteventset.c
@@ -348,7 +348,7 @@ InitializeWaitEventSupport(void)
 
 #ifdef WAIT_USE_KQUEUE
 	/* Ignore SIGURG, because we'll receive it via kqueue. */
-	pqsignal(SIGURG, SIG_IGN);
+	pqsignal(SIGURG, PG_SIG_IGN);
 #endif
 }
 
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 4fb18741dc5..14df4d9aaf8 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -3025,6 +3025,17 @@ die(SIGNAL_ARGS)
 	{
 		InterruptPending = true;
 		ProcDiePending = true;
+
+		/*
+		 * Record who sent the signal.  Will be 0 on platforms without
+		 * SA_SIGINFO, which is fine -- ProcessInterrupts() checks for that.
+		 * Only set on the first SIGTERM so we report the original sender.
+		 */
+		if (ProcDieSenderPid == 0)
+		{
+			ProcDieSenderPid = pg_siginfo->pid;
+			ProcDieSenderUid = pg_siginfo->uid;
+		}
 	}
 
 	/* for the cumulative stats system */
@@ -4308,17 +4319,17 @@ PostgresMain(const char *dbname, const char *username)
 		 * returns to outer loop.  This seems safer than forcing exit in the
 		 * midst of output during who-knows-what operation...
 		 */
-		pqsignal(SIGPIPE, SIG_IGN);
+		pqsignal(SIGPIPE, PG_SIG_IGN);
 		pqsignal(SIGUSR1, procsignal_sigusr1_handler);
-		pqsignal(SIGUSR2, SIG_IGN);
+		pqsignal(SIGUSR2, PG_SIG_IGN);
 		pqsignal(SIGFPE, FloatExceptionHandler);
 
 		/*
 		 * Reset some signals that are accepted by postmaster but not by
 		 * backend
 		 */
-		pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
-									 * platforms */
+		pqsignal(SIGCHLD, PG_SIG_DFL);	/* system() requires this on some
+										 * platforms */
 	}
 
 	/* Early initialization */
diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index 509f1114ef6..44a2c7a7c7f 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -2903,10 +2903,10 @@ setup_signals(void)
 	pqsignal(SIGQUIT, trapsig);
 
 	/* Ignore SIGPIPE when writing to backend, so we can clean up */
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 
 	/* Prevent SIGSYS so we can probe for kernel calls that might not work */
-	pqsignal(SIGSYS, SIG_IGN);
+	pqsignal(SIGSYS, PG_SIG_IGN);
 #endif
 }
 
diff --git a/src/bin/pg_ctl/pg_ctl.c b/src/bin/pg_ctl/pg_ctl.c
index 3cc61455dcb..5539eb8ebef 100644
--- a/src/bin/pg_ctl/pg_ctl.c
+++ b/src/bin/pg_ctl/pg_ctl.c
@@ -868,7 +868,7 @@ trap_sigint_during_startup(SIGNAL_ARGS)
 	 * Clear the signal handler, and send the signal again, to terminate the
 	 * process as normal.
 	 */
-	pqsignal(postgres_signal_arg, SIG_DFL);
+	pqsignal(postgres_signal_arg, PG_SIG_DFL);
 	raise(postgres_signal_arg);
 }
 
diff --git a/src/bin/pg_dump/parallel.c b/src/bin/pg_dump/parallel.c
index a28561fbd84..a7bed5ecccf 100644
--- a/src/bin/pg_dump/parallel.c
+++ b/src/bin/pg_dump/parallel.c
@@ -568,9 +568,9 @@ sigTermHandler(SIGNAL_ARGS)
 	 * signal handler.  That could muck up our attempt to send PQcancel, so
 	 * disable the signals that set_cancel_handler enabled.
 	 */
-	pqsignal(SIGINT, SIG_IGN);
-	pqsignal(SIGTERM, SIG_IGN);
-	pqsignal(SIGQUIT, SIG_IGN);
+	pqsignal(SIGINT, PG_SIG_IGN);
+	pqsignal(SIGTERM, PG_SIG_IGN);
+	pqsignal(SIGQUIT, PG_SIG_IGN);
 
 	/*
 	 * If we're in the leader, forward signal to all workers.  (It seems best
@@ -1049,7 +1049,7 @@ ParallelBackupStart(ArchiveHandle *AH)
 	 * the workers to inherit this setting, though.
 	 */
 #ifndef WIN32
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 #endif
 
 	/*
diff --git a/src/bin/psql/t/001_basic.pl b/src/bin/psql/t/001_basic.pl
index 7c21204c1f2..9d966c7bece 100644
--- a/src/bin/psql/t/001_basic.pl
+++ b/src/bin/psql/t/001_basic.pl
@@ -142,8 +142,11 @@ my ($ret, $out, $err) = $node->psql('postgres',
 is($ret, 2, 'server crash: psql exit code');
 like($out, qr/before/, 'server crash: output before crash');
 unlike($out, qr/AFTER/, 'server crash: no output after crash');
+my $detail_re = check_pg_config("#define HAVE_SA_SIGINFO 1")
+	? qr/DETAIL:  Signal sent by PID \d+, UID \d+\.\n/
+	: qr//;
 like( $err, qr/psql:<stdin>:2: FATAL:  terminating connection due to administrator command
-(?:DETAIL:  Signal sent by PID \d+, UID \d+\.\n)?psql:<stdin>:2: server closed the connection unexpectedly
+${detail_re}psql:<stdin>:2: server closed the connection unexpectedly
 	This probably means the server terminated abnormally
 	before or while processing the request.
 psql:<stdin>:2: error: connection to server was lost/,
diff --git a/src/fe_utils/print.c b/src/fe_utils/print.c
index 12d969e8666..f2dd52003c1 100644
--- a/src/fe_utils/print.c
+++ b/src/fe_utils/print.c
@@ -3024,7 +3024,7 @@ void
 disable_sigpipe_trap(void)
 {
 #ifndef WIN32
-	pqsignal(SIGPIPE, SIG_IGN);
+	pqsignal(SIGPIPE, PG_SIG_IGN);
 #endif
 }
 
@@ -3047,7 +3047,7 @@ void
 restore_sigpipe_trap(void)
 {
 #ifndef WIN32
-	pqsignal(SIGPIPE, always_ignore_sigpipe ? SIG_IGN : SIG_DFL);
+	pqsignal(SIGPIPE, always_ignore_sigpipe ? PG_SIG_IGN : PG_SIG_DFL);
 #endif
 }
 
diff --git a/src/include/c.h b/src/include/c.h
index 88d13ec9993..7e11ba5f8c3 100644
--- a/src/include/c.h
+++ b/src/include/c.h
@@ -1441,17 +1441,28 @@ extern int	fdatasync(int fd);
 #endif
 
 /*
- * The following is used as the arg list for signal handlers.  Any ports
- * that take something other than an int argument should override this in
- * their pg_config_os.h file.  Note that variable names are required
- * because it is used in both the prototypes as well as the definitions.
- * Note also the long name.  We expect that this won't collide with
- * other names causing compiler warnings.
+ * Platform independent struct representing additional information about the
+ * received signal.  If the system does not support the extended information,
+ * or a field does not apply to the signal, the value is instead reset to the
+ * documented default value.
  */
 
-#ifndef SIGNAL_ARGS
-#define SIGNAL_ARGS  int postgres_signal_arg
-#endif
+typedef struct pg_signal_info
+{
+	uint32_t		pid;			/* pid of sending process or 0 if unknown */
+	uint32_t		uid;			/* uid of sending process; only meaningful
+								 * when pid is not 0 */
+} pg_signal_info;
+
+/*
+ * The following is used as the arg list for signal handlers. These days we
+ * use the same argument to all signal handlers and hide the difference
+ * between platforms in wrapper functions.
+ *
+ * SIGNAL_ARGS just exists separately from the pqsignal() definition for
+ * historical reasons.
+ */
+#define SIGNAL_ARGS  int postgres_signal_arg, const pg_signal_info *pg_siginfo
 
 /*
  * When there is no sigsetjmp, its functionality is provided by plain
diff --git a/src/include/port.h b/src/include/port.h
index 51df9b80e7d..c029878c6be 100644
--- a/src/include/port.h
+++ b/src/include/port.h
@@ -546,6 +546,9 @@ extern int	pg_mkdir_p(char *path, int omode);
 #else
 #define pqsignal pqsignal_be
 #endif
+
+#define PG_SIG_DFL (pqsigfunc) (pg_funcptr_t) SIG_DFL
+#define PG_SIG_IGN (pqsigfunc) (pg_funcptr_t) SIG_IGN
 typedef void (*pqsigfunc) (SIGNAL_ARGS);
 extern void pqsignal(int signo, pqsigfunc func);
 
diff --git a/src/interfaces/libpq/legacy-pqsignal.c b/src/interfaces/libpq/legacy-pqsignal.c
index 1285b033e1b..0735e4ee0d5 100644
--- a/src/interfaces/libpq/legacy-pqsignal.c
+++ b/src/interfaces/libpq/legacy-pqsignal.c
@@ -36,10 +36,12 @@
  * is to ensure that no in-tree code accidentally calls this version.)
  */
 #undef pqsignal
-extern pqsigfunc pqsignal(int signo, pqsigfunc func);
 
-pqsigfunc
-pqsignal(int signo, pqsigfunc func)
+typedef void (*pqsigfunc_legacy) (int postgres_signal_arg);
+extern pqsigfunc_legacy pqsignal(int signo, pqsigfunc_legacy func);
+
+pqsigfunc_legacy
+pqsignal(int signo, pqsigfunc_legacy func)
 {
 #ifndef WIN32
 	struct sigaction act,
diff --git a/src/port/pqsignal.c b/src/port/pqsignal.c
index 8841464b5cb..93c908ee566 100644
--- a/src/port/pqsignal.c
+++ b/src/port/pqsignal.c
@@ -63,6 +63,14 @@
 #define PG_NSIG (64)			/* XXX: wild guess */
 #endif
 
+#if !(defined(WIN32) && defined(FRONTEND))
+#define USE_SIGACTION
+#endif
+
+#if defined(USE_SIGACTION) && defined(HAVE_SA_SIGINFO)
+#define USE_SIGINFO
+#endif
+
 /* Check a couple of common signals to make sure PG_NSIG is accurate. */
 StaticAssertDecl(SIGUSR2 < PG_NSIG, "SIGUSR2 >= PG_NSIG");
 StaticAssertDecl(SIGHUP < PG_NSIG, "SIGHUP >= PG_NSIG");
@@ -82,19 +90,16 @@ static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
  *
  * This wrapper also handles restoring the value of errno.
  */
-#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
+#if defined(USE_SIGACTION) && defined(USE_SIGINFO)
 static void
-wrapper_handler(int signo, siginfo_t * info, void *context)
-#else
+wrapper_handler(int postgres_signal_arg, siginfo_t *info, void *context)
+#else /* no USE_SIGINFO */
 static void
-wrapper_handler(SIGNAL_ARGS)
+wrapper_handler(int postgres_signal_arg)
 #endif
 {
 	int			save_errno = errno;
-#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
-	/* SA_SIGINFO signature uses signo, not SIGNAL_ARGS macro */
-	int			postgres_signal_arg = signo;
-#endif
+	pg_signal_info pg_info;
 
 	Assert(postgres_signal_arg > 0);
 	Assert(postgres_signal_arg < PG_NSIG);
@@ -110,21 +115,32 @@ wrapper_handler(SIGNAL_ARGS)
 
 	if (unlikely(MyProcPid != (int) getpid()))
 	{
-		pqsignal(postgres_signal_arg, SIG_DFL);
+		pqsignal(postgres_signal_arg, PG_SIG_DFL);
 		raise(postgres_signal_arg);
 		return;
 	}
+#endif
 
 #ifdef HAVE_SA_SIGINFO
-	if (signo == SIGTERM && info)
-	{
-		ProcDieSenderPid = info->si_pid;
-		ProcDieSenderUid = info->si_uid;
-	}
-#endif
+
+	/*
+	 * If supported by the system, forward interesting information from the
+	 * system's extended signal information to our platform independent
+	 * format.
+	 */
+	pg_info.pid = info->si_pid;
+	pg_info.uid = info->si_uid;
+#else
+
+	/*
+	 * Otherwise forward values indicating that we do not have the
+	 * information.
+	 */
+	pg_info.pid = 0;
+	pg_info.uid = 0;
 #endif
 
-	(*pqsignal_handlers[postgres_signal_arg]) (postgres_signal_arg);
+	(*pqsignal_handlers[postgres_signal_arg]) (postgres_signal_arg, &pg_info);
 
 	errno = save_errno;
 }
@@ -139,33 +155,44 @@ wrapper_handler(SIGNAL_ARGS)
 void
 pqsignal(int signo, pqsigfunc func)
 {
-#if !(defined(WIN32) && defined(FRONTEND))
+#ifdef USE_SIGACTION
 	struct sigaction act;
+#else
+	void (*wrapper_func_ptr)(int);
 #endif
-	bool		use_wrapper = false;
+	bool		is_ign = func == PG_SIG_IGN;
+	bool		is_dfl = func == PG_SIG_DFL;
 
 	Assert(signo > 0);
 	Assert(signo < PG_NSIG);
 
-	if (func != SIG_IGN && func != SIG_DFL)
+	/* set up indirection handler */
+	if (!(is_ign || is_dfl))
 	{
 		pqsignal_handlers[signo] = func;	/* assumed atomic */
-		use_wrapper = true;
 	}
 
-#if !(defined(WIN32) && defined(FRONTEND))
+	/*
+	 * Configure system to either ignore/reset the signal handler, or to
+	 * forward it to wrapper_handler.
+	 */
+#ifdef USE_SIGACTION
 	sigemptyset(&act.sa_mask);
 	act.sa_flags = SA_RESTART;
-#if !defined(FRONTEND) && defined(HAVE_SA_SIGINFO)
-	if (use_wrapper)
+
+	if (is_ign)
+		act.sa_handler = SIG_IGN;
+	else if (is_dfl)
+		act.sa_handler = SIG_DFL;
+#ifdef USE_SIGINFO
+	else
 	{
 		act.sa_sigaction = wrapper_handler;
 		act.sa_flags |= SA_SIGINFO;
 	}
-	else
-		act.sa_handler = func;
 #else
-	act.sa_handler = use_wrapper ? wrapper_handler : func;
+	else
+		act.sa_handler = wrapper_handler;
 #endif
 
 #ifdef SA_NOCLDSTOP
@@ -174,9 +201,19 @@ pqsignal(int signo, pqsigfunc func)
 #endif
 	if (sigaction(signo, &act, NULL) < 0)
 		Assert(false);			/* probably indicates coding error */
-#else
-	/* Forward to Windows native signal system. */
-	if (signal(signo, use_wrapper ? wrapper_handler : func) == SIG_ERR)
+#else /* no USE_SIGACTION */
+	/*
+	 * Forward to Windows native signal system, we need to send this though
+	 * wrapper handler as it it needs to take single argument only.
+	 */
+	if(is_ign)
+		wrapper_func_ptr = SIG_IGN;
+	else if (is_dfl)
+		wrapper_func_ptr = SIG_DFL;
+	else
+		wrapper_func_ptr = wrapper_handler;
+
+	if (signal(signo, wrapper_func_ptr) == SIG_ERR)
 		Assert(false);			/* probably indicates coding error */
 #endif
 }
diff --git a/src/test/regress/pg_regress.c b/src/test/regress/pg_regress.c
index 9a918156437..a554542aa2a 100644
--- a/src/test/regress/pg_regress.c
+++ b/src/test/regress/pg_regress.c
@@ -492,7 +492,7 @@ signal_remove_temp(SIGNAL_ARGS)
 {
 	remove_temp();
 
-	pqsignal(postgres_signal_arg, SIG_DFL);
+	pqsignal(postgres_signal_arg, PG_SIG_DFL);
 	raise(postgres_signal_arg);
 }
 
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index e9430e07b36..97f1e474212 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -4022,6 +4022,7 @@ pg_sha224_ctx
 pg_sha256_ctx
 pg_sha384_ctx
 pg_sha512_ctx
+pg_signal_info
 pg_snapshot
 pg_special_case
 pg_stack_base_t
-- 
2.43.0



^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-15 06:11  Chao Li <li.evan.chao@gmail.com>
  parent: Andrew Dunstan <andrew@dunslane.net>
  1 sibling, 1 reply; 54+ messages in thread

From: Chao Li @ 2026-04-15 06:11 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Jakub Wartak <jakub.wartak@enterprisedb.com>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>



> On Apr 15, 2026, at 04:38, Andrew Dunstan <andrew@dunslane.net> wrote:
> 
> 
> On 2026-04-14 Tu 6:40 AM, Jakub Wartak wrote:
>> Hi Andres, Andrew, Chao
>> 
>> thanks for putting so much effort into enhancing the the previous implementation
>> of this code. Earlier I was not aware of potential problems involved.
>> 
>> On Fri, Apr 10, 2026 at 9:41 AM Chao Li <li.evan.chao@gmail.com> wrote:
>>> 
>>> 
>>>> On Apr 9, 2026, at 18:59, Andrew Dunstan <andrew@dunslane.net> wrote:
>>>> 
>>>> 
>>>> On 2026-04-08 We 1:01 PM, Andres Freund wrote:
>>>>> Hi,
>>>>> 
>>>>> Attached is a very rough first draft for how I think this needs to look like.
>>>>> 
>>>>> Basically, SIGNAL_INFO always will pass both the signal number and extended
>>>>> information along to the signal handler. The extended information is a
>>>>> postgres specific struct. If the platform can't provide the extended
>>>>> information, the values are instead set to some default value indicating that
>>>>> the information is not known.
>>>>> 
>>>>> With that die() (and also StatementCancelHandler, ...) can just set whatever
>>>>> globals it wants, without pqsignal.c needing to know about it.
>>>>> 
>>>>> It also allows us to extend the amount of information in the future. E.g. I'd
>>>>> like to log the reason for a segfault (could e.g. be an OOM kill or an umapped
>>>>> region) to stderr.
>>>>> 
>>>>> The annoying thing about it is needing to change nearly all the existing
>>>>> references to SIG_IGN/SIG_DFL, to avoid warnings due to mismatched types.
>>>> I agree that's annoying. The only way around it I found was via some casting to/from void* that I suspect you would find a cure worse than the disease.
>>>> I reworked your patch slightly. This version fixes the translatability issue you raised earlier, makes the TAP test from the original commit more robust, and  tries to resolve your XXX issue by moving the assignment of ProcDieSenderPid/Uid inside the "if (!proc_exit_inprogress)" block.
>>>> 
>>> I reviewed this version. Besides the compile warning and uid 0 issues, I got a few more comments, so I try to put them all together as below.
>>> 
>> TL;DR; win/mingw is really unhappy with the state of rework patch right now.
>> I've tried to enhance and fix it, and now it's green for default CI run and
>> also for mingw too. Attached 0002-fixup-win32 patch does not incorporate Chao's
>> all findings so far.
>> 
>> [..]
>>> 2 - uid 0 problem
>>> ```
>>> +typedef struct pg_signal_info
>>> +{
>>> +       pid_t           pid;                    /* pid of sending process or 0 if unknown */
>>> +       uid_t           uid;                    /* uid of sending process or 0 if unknown */
>>> +} pg_signal_info;
>>> ```
>>> 
>>> I think we can mention that “uid” is only meaningful when pid is set.
>> [..]
>>> 5
>>> ```
>>> +       pg_info.uid = 0;
>>> ```
>>> 
>>> If you take comment 2, then when unavailable, we can just don’t assign anything to pg_info.uid. Or "(uid_t)-1", maybe.
>>> 
>> 
>> I. I've started from this and I vaguley remembered that I had terrible
>> experience
>> when trying to chose the proper types for those field types, but I couldn't
>> remind myself why, so I've gave a try of the current rework patch and got this
>> on Windows Server 2022, vs2019, cirrus-ci said:
>> 
>> [08:40:22.848] c:\cirrus\src\include\c.h(1451): error C2061: syntax
>> error: identifier 'pid_t'
>> [08:40:22.848] c:\cirrus\src\include\c.h(1452): error C2061: syntax
>> error: identifier 'uid'
>> [08:40:22.848] c:\cirrus\src\include\c.h(1452): error C2059: syntax error: ';'
>> [08:40:22.848] c:\cirrus\src\include\c.h(1453): error C2059: syntax error: '}'
>> 
>> for c.h:
>>   1449  typedef struct pg_signal_info
>>   1450  {
>>   1451          pid_t           pid;                    /* pid of
>> sending process or 0 if unknown */
>>   1452          uid_t           uid;                    /* uid of
>> sending process or 0 if unknown */
>>   1453  } pg_signal_info;
>> 
>> so maybe we should just move that typedef with SIGNAL_ARGS to after
>> "include of port.h" (line ~1471) in that c.h, because only then we'll have
>> access to:
>>     src/include/port/win32_port.h:typedef int pid_t;
>>     src/include/port/win32_port.h:typedef int uid_t;
>> but the problem is that port.h itself requires SIGNAL_ARGS to be defined
>> and that seems to be like chicken and egg problem.  I thought that just
>> using native "ints" could be the way to go, but the problem is that now
>> that uid_t can be bigger than pid_t as Linux kernel headers show this:
>> 
>> x86_64-linux-gnu/bits/types.h:#define   __S32_TYPE              int
>> x86_64-linux-gnu/bits/types.h:#define __U32_TYPE                unsigned int
>> x86_64-linux-gnu/bits/types.h:__STD_TYPE __UID_T_TYPE __uid_t;  /*
>> Type of user identifications.  */
>> x86_64-linux-gnu/bits/types.h:__STD_TYPE __PID_T_TYPE __pid_t;  /*
>> Type of process identifications.  */
>> x86_64-linux-gnu/bits/typesizes.h:#define __UID_T_TYPE          __U32_TYPE
>> x86_64-linux-gnu/bits/typesizes.h:#define __PID_T_TYPE          __S32_TYPE
>> 
>> so maybe do that typedef struct pg_signal_info with 2x uint32_t and that's
>> good enough? (it covers the ranges necessary and makes it platform compatible)
>> 
>> II. While we are tthis so with above uid_t of up to being u32, possibly
>> `volatile int ProcDieSenderUid/Pid` should be also bigger like uint32_t?
>> My fixup-patch does not incude it, because I don't know really.
>> 
>> III. As Chao said I've used:
>> 
>> +#define PG_SIG_DFL (pqsigfunc) (pg_funcptr_t) SIG_DFL
>> +#define PG_SIG_IGN (pqsigfunc) (pg_funcptr_t) SIG_IGN
>> 
>> IV.  Then just got lots of warnings for use_wrapper/wrapp_handler and so on
>> 
>> [09:27:33.602] ../src/port/pqsignal.c(206): error C2065:
>> 'use_wrapper': undeclared identifier
>> [09:27:33.602] ../src/port/pqsignal.c(206): warning C4113: 'pqsigfunc'
>> differs in parameter lists from 'void (__cdecl *)(int)'
>> 
>> that's for:
>>    204  #else
>>    205          /* Forward to Windows native signal system. */
>>    206          if (signal(signo, use_wrapper ? wrapper_handler :
>> func) == SIG_ERR)
>>    207                  Assert(false);                  /* probably
>> indicates coding error */
>> 
>> In the end, I've ended up using wrapper_handler for the windows path there
>> as signal() requires function with single param.
>> 
>> IV. Got some further issues, and VC complained that siginfo_t is used for
>> USE_SIGACTION - isn't it impossible on win32? Anyway, that makes some sense,
>> USE_SIGINFO is not defined and we use 'siginfo_t', so something like fixes it:
>> 
>> @@ -90,7 +90,7 @@ static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
>>   *
>>   * This wrapper also handles restoring the value of errno.
>>   */
>> -#ifdef USE_SIGACTION
>> +#if defined(USE_SIGACTION) && defined(USE_SIGINFO)
>>  static void
>>  wrapper_handler(int postgres_signal_arg, siginfo_t *info, void *context)
>>  #else
>> 
>> V. Later I've stumbled on series of other problems related to
>> src/backend/port/win32/signal.c (it also uses SIG_DFL but not PG_SIG_DFL and
>> stil somewhat references pgsigfunc, so those changes seemed to impact it).
>> 
>> Also there was:
>> [10:37:02.824] ../src/backend/port/win32/signal.c(154): error C2198:
>> 'sig': too few arguments for call
>> 
>> so I've fixed with adding nodata struct there and:
>> @@ -151,7 +154,7 @@ pgwin32_dispatch_queued_signals(void)
>>                                                 block_mask |= sigmask(i);
>> 
>>                                         sigprocmask(SIG_BLOCK,
>> &block_mask, &save_mask);
>> -                                       sig(i);
>> +                                       sig(i, &nodata);
>>                                         sigprocmask(SIG_SETMASK,
>> &save_mask, NULL);
>> 
>> VI. Possibly we could rename USE_SIGACTION define because at least to me it
>> is confusing to me to reason and communicate about in terms of win32 context
>> on win32 do we do have it or not? (it can be both ways):
>> * win32 C API doesnt have it
>> * PG does have sigaction win32 wrapper with override macro
>>   #define sigaction.. pqsigaction..
>> * however src/include/libpq/pqsignal.h says "sa_sigaction not yet implemented"
>>   for it (so with USE_SIGACTION are we talking about sa_sigaction field memeber
>>   that it's not used or about sigaction function?)
>> 
>> VII. FWIW, I've also removed superflous "else"
>>  #ifdef USE_SIGINFO
>>         if (!(is_ign || is_dfl))
>>         {
>>                 act.sa_sigaction = wrapper_handler;
>>                 act.sa_flags |= SA_SIGINFO;
>>         }
>> -       else
>>  #else
>> 
>> 
> 
> 
> I'm not 100% sure that else shouldn't be there. Maybe have another look?
> 
> Attached is a consolidation that includes your other fixes, plus:
> 
> . uid comment -- "only meaningful when pid is not 0"
> . const pg_signal_info *pg_siginfo in SIGNAL_ARGS
> . 2 spaces after period in syncrep.c errdetail
> 
> 
> cheers
> 
> 
> andrew
> 
> 
> 
> --
> Andrew Dunstan
> EDB: https://www.enterprisedb.com
> <v2-0001-Rework-signal-handler-infrastructure-to-pass-send.patch>

V2 LGTM.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/









^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-15 09:27  Jakub Wartak <jakub.wartak@enterprisedb.com>
  parent: Andrew Dunstan <andrew@dunslane.net>
  1 sibling, 2 replies; 54+ messages in thread

From: Jakub Wartak @ 2026-04-15 09:27 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Chao Li <li.evan.chao@gmail.com>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Tue, Apr 14, 2026 at 10:38 PM Andrew Dunstan <andrew@dunslane.net> wrote:
>
>
> On 2026-04-14 Tu 6:40 AM, Jakub Wartak wrote:
> > Hi Andres, Andrew, Chao
> >
> > thanks for putting so much effort into enhancing the the previous implementation
> > of this code. Earlier I was not aware of potential problems involved.
> >
> > On Fri, Apr 10, 2026 at 9:41 AM Chao Li <li.evan.chao@gmail.com> wrote:
> >>
> >>
> >>> On Apr 9, 2026, at 18:59, Andrew Dunstan <andrew@dunslane.net> wrote:
> >>>
> >>>
> >>> On 2026-04-08 We 1:01 PM, Andres Freund wrote:
> >>>> Hi,
> >>>>
> >>>> Attached is a very rough first draft for how I think this needs to look like.
> >>>>
> >>>> Basically, SIGNAL_INFO always will pass both the signal number and extended
> >>>> information along to the signal handler. The extended information is a
> >>>> postgres specific struct. If the platform can't provide the extended
> >>>> information, the values are instead set to some default value indicating that
> >>>> the information is not known.
> >>>>
> >>>> With that die() (and also StatementCancelHandler, ...) can just set whatever
> >>>> globals it wants, without pqsignal.c needing to know about it.
> >>>>
> >>>> It also allows us to extend the amount of information in the future. E.g. I'd
> >>>> like to log the reason for a segfault (could e.g. be an OOM kill or an umapped
> >>>> region) to stderr.
> >>>>
> >>>> The annoying thing about it is needing to change nearly all the existing
> >>>> references to SIG_IGN/SIG_DFL, to avoid warnings due to mismatched types.
> >>> I agree that's annoying. The only way around it I found was via some casting to/from void* that I suspect you would find a cure worse than the disease.
> >>> I reworked your patch slightly. This version fixes the translatability issue you raised earlier, makes the TAP test from the original commit more robust, and  tries to resolve your XXX issue by moving the assignment of ProcDieSenderPid/Uid inside the "if (!proc_exit_inprogress)" block.
> >>>
> >> I reviewed this version. Besides the compile warning and uid 0 issues, I got a few more comments, so I try to put them all together as below.
> >>
> > TL;DR; win/mingw is really unhappy with the state of rework patch right now.
> > I've tried to enhance and fix it, and now it's green for default CI run and
> > also for mingw too. Attached 0002-fixup-win32 patch does not incorporate Chao's
> > all findings so far.
> >
> > [..]
> >> 2 - uid 0 problem
> >> ```
> >> +typedef struct pg_signal_info
> >> +{
> >> +       pid_t           pid;                    /* pid of sending process or 0 if unknown */
> >> +       uid_t           uid;                    /* uid of sending process or 0 if unknown */
> >> +} pg_signal_info;
> >> ```
> >>
> >> I think we can mention that “uid” is only meaningful when pid is set.
> > [..]
> >> 5
> >> ```
> >> +       pg_info.uid = 0;
> >> ```
> >>
> >> If you take comment 2, then when unavailable, we can just don’t assign anything to pg_info.uid. Or "(uid_t)-1", maybe.
> >>
> >
> > I. I've started from this and I vaguley remembered that I had terrible
> > experience
> > when trying to chose the proper types for those field types, but I couldn't
> > remind myself why, so I've gave a try of the current rework patch and got this
> > on Windows Server 2022, vs2019, cirrus-ci said:
> >
> > [08:40:22.848] c:\cirrus\src\include\c.h(1451): error C2061: syntax
> > error: identifier 'pid_t'
> > [08:40:22.848] c:\cirrus\src\include\c.h(1452): error C2061: syntax
> > error: identifier 'uid'
> > [08:40:22.848] c:\cirrus\src\include\c.h(1452): error C2059: syntax error: ';'
> > [08:40:22.848] c:\cirrus\src\include\c.h(1453): error C2059: syntax error: '}'
> >
> > for c.h:
> >    1449  typedef struct pg_signal_info
> >    1450  {
> >    1451          pid_t           pid;                    /* pid of
> > sending process or 0 if unknown */
> >    1452          uid_t           uid;                    /* uid of
> > sending process or 0 if unknown */
> >    1453  } pg_signal_info;
> >
> > so maybe we should just move that typedef with SIGNAL_ARGS to after
> > "include of port.h" (line ~1471) in that c.h, because only then we'll have
> > access to:
> >      src/include/port/win32_port.h:typedef int pid_t;
> >      src/include/port/win32_port.h:typedef int uid_t;
> > but the problem is that port.h itself requires SIGNAL_ARGS to be defined
> > and that seems to be like chicken and egg problem.  I thought that just
> > using native "ints" could be the way to go, but the problem is that now
> > that uid_t can be bigger than pid_t as Linux kernel headers show this:
> >
> > x86_64-linux-gnu/bits/types.h:#define   __S32_TYPE              int
> > x86_64-linux-gnu/bits/types.h:#define __U32_TYPE                unsigned int
> > x86_64-linux-gnu/bits/types.h:__STD_TYPE __UID_T_TYPE __uid_t;  /*
> > Type of user identifications.  */
> > x86_64-linux-gnu/bits/types.h:__STD_TYPE __PID_T_TYPE __pid_t;  /*
> > Type of process identifications.  */
> > x86_64-linux-gnu/bits/typesizes.h:#define __UID_T_TYPE          __U32_TYPE
> > x86_64-linux-gnu/bits/typesizes.h:#define __PID_T_TYPE          __S32_TYPE
> >
> > so maybe do that typedef struct pg_signal_info with 2x uint32_t and that's
> > good enough? (it covers the ranges necessary and makes it platform compatible)
> >
> > II. While we are tthis so with above uid_t of up to being u32, possibly
> > `volatile int ProcDieSenderUid/Pid` should be also bigger like uint32_t?
> > My fixup-patch does not incude it, because I don't know really.
> >
> > III. As Chao said I've used:
> >
> > +#define PG_SIG_DFL (pqsigfunc) (pg_funcptr_t) SIG_DFL
> > +#define PG_SIG_IGN (pqsigfunc) (pg_funcptr_t) SIG_IGN
> >
> > IV.  Then just got lots of warnings for use_wrapper/wrapp_handler and so on
> >
> > [09:27:33.602] ../src/port/pqsignal.c(206): error C2065:
> > 'use_wrapper': undeclared identifier
> > [09:27:33.602] ../src/port/pqsignal.c(206): warning C4113: 'pqsigfunc'
> > differs in parameter lists from 'void (__cdecl *)(int)'
> >
> > that's for:
> >     204  #else
> >     205          /* Forward to Windows native signal system. */
> >     206          if (signal(signo, use_wrapper ? wrapper_handler :
> > func) == SIG_ERR)
> >     207                  Assert(false);                  /* probably
> > indicates coding error */
> >
> > In the end, I've ended up using wrapper_handler for the windows path there
> > as signal() requires function with single param.
> >
> > IV. Got some further issues, and VC complained that siginfo_t is used for
> > USE_SIGACTION - isn't it impossible on win32? Anyway, that makes some sense,
> > USE_SIGINFO is not defined and we use 'siginfo_t', so something like fixes it:
> >
> > @@ -90,7 +90,7 @@ static volatile pqsigfunc pqsignal_handlers[PG_NSIG];
> >    *
> >    * This wrapper also handles restoring the value of errno.
> >    */
> > -#ifdef USE_SIGACTION
> > +#if defined(USE_SIGACTION) && defined(USE_SIGINFO)
> >   static void
> >   wrapper_handler(int postgres_signal_arg, siginfo_t *info, void *context)
> >   #else
> >
> > V. Later I've stumbled on series of other problems related to
> > src/backend/port/win32/signal.c (it also uses SIG_DFL but not PG_SIG_DFL and
> > stil somewhat references pgsigfunc, so those changes seemed to impact it).
> >
> > Also there was:
> > [10:37:02.824] ../src/backend/port/win32/signal.c(154): error C2198:
> > 'sig': too few arguments for call
> >
> > so I've fixed with adding nodata struct there and:
> > @@ -151,7 +154,7 @@ pgwin32_dispatch_queued_signals(void)
> >                                                  block_mask |= sigmask(i);
> >
> >                                          sigprocmask(SIG_BLOCK,
> > &block_mask, &save_mask);
> > -                                       sig(i);
> > +                                       sig(i, &nodata);
> >                                          sigprocmask(SIG_SETMASK,
> > &save_mask, NULL);
> >
> > VI. Possibly we could rename USE_SIGACTION define because at least to me it
> > is confusing to me to reason and communicate about in terms of win32 context
> > on win32 do we do have it or not? (it can be both ways):
> > * win32 C API doesnt have it
> > * PG does have sigaction win32 wrapper with override macro
> >    #define sigaction.. pqsigaction..
> > * however src/include/libpq/pqsignal.h says "sa_sigaction not yet implemented"
> >    for it (so with USE_SIGACTION are we talking about sa_sigaction field memeber
> >    that it's not used or about sigaction function?)
> >
> > VII. FWIW, I've also removed superflous "else"
> >   #ifdef USE_SIGINFO
> >          if (!(is_ign || is_dfl))
> >          {
> >                  act.sa_sigaction = wrapper_handler;
> >                  act.sa_flags |= SA_SIGINFO;
> >          }
> > -       else
> >   #else
> >
> >
>
>
> I'm not 100% sure that else shouldn't be there. Maybe have another look?


So in 0001 we had pqsignal() like below:

```
#ifdef USE_SIGINFO
        if (!(is_ign || is_dfl))
        {
                act.sa_sigaction = wrapper_handler;
                act.sa_flags |= SA_SIGINFO;
        }
        else // <--- this is the problematic line that I wanted to remove
#else
        else
                act.sa_handler = wrapper_handler;
#endif

#ifdef SA_NOCLDSTOP
        if (signo == SIGCHLD)
                act.sa_flags |= SA_NOCLDSTOP;
#endif
```
(in latest v2-0001 it seems to be refactored and looks more readable to me)

IMHO it was superflous for the following reasons:
a) previous releases did not have such condition (flow went unconditially to
   `if (signo == SIGCHLD)` and not based on function spec. in a lot of places we
   call `pqsignal(SIGCHLD, PG_SIG_DFL)` but in PostmasterMain() we call
   `pqsignal(SIGCHLD, handle_pm_child_exit_signal);` so we should set
   SA_NOCLDSTOP in both cases not just one.

b) if the platform wouldn't have SA_NOCLDSTOP, so stil with USE_SIGACTION (it
   would have to be basically non POSIX.1-1990, but not WIN32, so impossible?),
   that would shift the code flow to later lines (sigaction() itself) so
   that would be a bug

I would say I would even propose removal of #ifdef SA_NOCLDSTOP and assume it's
always there, as personally I hate such macro complexity.

BTW tiny nitpick to myself:
--- a/src/port/pqsignal.c
+++ b/src/port/pqsignal.c
@@ -206,7 +206,7 @@ pqsignal(int signo, pqsigfunc func)
         * Forward to Windows native signal system, we need to send this though
         * wrapper handler as it it needs to take single argument only.
         */
-       if(is_ign)
+       if (is_ign)


> Attached is a consolidation that includes your other fixes, plus:
>
> . uid comment -- "only meaningful when pid is not 0"
> . const pg_signal_info *pg_siginfo in SIGNAL_ARGS
> . 2 spaces after period in syncrep.c errdetail

v2-0001 LGTM.

-J.





^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-15 11:37  Andrew Dunstan <andrew@dunslane.net>
  parent: Jakub Wartak <jakub.wartak@enterprisedb.com>
  1 sibling, 1 reply; 54+ messages in thread

From: Andrew Dunstan @ 2026-04-15 11:37 UTC (permalink / raw)
  To: Jakub Wartak <jakub.wartak@enterprisedb.com>; +Cc: Chao Li <li.evan.chao@gmail.com>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>


On 2026-04-15 We 5:27 AM, Jakub Wartak wrote:
> v2-0001 LGTM.
>

OK, pushed. Thanks.


cheers


andrew

--
Andrew Dunstan
EDB: https://www.enterprisedb.com






^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-15 11:45  Kirill Reshke <reshkekirill@gmail.com>
  parent: Chao Li <li.evan.chao@gmail.com>
  0 siblings, 1 reply; 54+ messages in thread

From: Kirill Reshke @ 2026-04-15 11:45 UTC (permalink / raw)
  To: Chao Li <li.evan.chao@gmail.com>; +Cc: Andrew Dunstan <andrew@dunslane.net>; Jakub Wartak <jakub.wartak@enterprisedb.com>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

I am seeing 3e2a1496bae628c379ca0a11ef5f5ba666f24ae8 merged into
master today, and I am a bit surprised.

This is a feature for my taste and the feature freeze was on 8th April
12 UTC. Am I wrong?

-- 
Best regards,
Kirill Reshke





^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-15 12:14  Andrew Dunstan <andrew@dunslane.net>
  parent: Kirill Reshke <reshkekirill@gmail.com>
  0 siblings, 1 reply; 54+ messages in thread

From: Andrew Dunstan @ 2026-04-15 12:14 UTC (permalink / raw)
  To: Kirill Reshke <reshkekirill@gmail.com>; Chao Li <li.evan.chao@gmail.com>; +Cc: Jakub Wartak <jakub.wartak@enterprisedb.com>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>


On 2026-04-15 We 7:45 AM, Kirill Reshke wrote:
> I am seeing 3e2a1496bae628c379ca0a11ef5f5ba666f24ae8 merged into
> master today, and I am a bit surprised.
>
> This is a feature for my taste and the feature freeze was on 8th April
> 12 UTC. Am I wrong?
>


It's a fix for a feature that was committed before feature freeze.


cheers


andrew

--
Andrew Dunstan
EDB: https://www.enterprisedb.com






^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-15 12:45  Kirill Reshke <reshkekirill@gmail.com>
  parent: Andrew Dunstan <andrew@dunslane.net>
  0 siblings, 0 replies; 54+ messages in thread

From: Kirill Reshke @ 2026-04-15 12:45 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Chao Li <li.evan.chao@gmail.com>; Jakub Wartak <jakub.wartak@enterprisedb.com>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Wed, 15 Apr 2026 at 17:14, Andrew Dunstan <andrew@dunslane.net> wrote:
>
>
> On 2026-04-15 We 7:45 AM, Kirill Reshke wrote:
> > I am seeing 3e2a1496bae628c379ca0a11ef5f5ba666f24ae8 merged into
> > master today, and I am a bit surprised.
> >
> > This is a feature for my taste and the feature freeze was on 8th April
> > 12 UTC. Am I wrong?
> >
>
>
> It's a fix for a feature that was committed before feature freeze.
>
>
> cheers
>
>
> andrew
>
> --
> Andrew Dunstan
> EDB: https://www.enterprisedb.com


Ok, sorry


-- 
Best regards,
Kirill Reshke





^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-15 14:37  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Jakub Wartak <jakub.wartak@enterprisedb.com>
  1 sibling, 2 replies; 54+ messages in thread

From: Tom Lane @ 2026-04-15 14:37 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Jakub Wartak <jakub.wartak@enterprisedb.com>; Chao Li <li.evan.chao@gmail.com>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Andrew Dunstan <andrew@dunslane.net> writes:
> OK, pushed. Thanks.

The OpenBSD members of the buildfarm don't seem to like this.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-15 15:26  Andrew Dunstan <andrew@dunslane.net>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 0 replies; 54+ messages in thread

From: Andrew Dunstan @ 2026-04-15 15:26 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Jakub Wartak <jakub.wartak@enterprisedb.com>; Chao Li <li.evan.chao@gmail.com>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>


On 2026-04-15 We 10:37 AM, Tom Lane wrote:
> Andrew Dunstan <andrew@dunslane.net> writes:
>> OK, pushed. Thanks.
> The OpenBSD members of the buildfarm don't seem to like this.
>
> 			


Ugh.


I'm will take a look later today.


cheers


andrew


--
Andrew Dunstan
EDB: https://www.enterprisedb.com






^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-15 16:04  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 1 reply; 54+ messages in thread

From: Tom Lane @ 2026-04-15 16:04 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Jakub Wartak <jakub.wartak@enterprisedb.com>; Chao Li <li.evan.chao@gmail.com>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Andrew Dunstan <andrew@dunslane.net> writes:
> On 2026-04-15 We 10:37 AM, Tom Lane wrote:
>> The OpenBSD members of the buildfarm don't seem to like this.

> Ugh.
> I'm will take a look later today.

I reproduced it locally on OpenBSD 7.7.  HAVE_SA_SIGINFO is defined,
and the code to grab the pid/uid out of siginfo_t is definitely
getting compiled.  As best I can tell, the kernel is simply passing
zero for info->si_pid and si_uid.  This does not match up with the
info available on the net, so I'm not sure what the issue is.

Some googling suggested that on some platforms si_pid will be zero
if the process signaled itself, but I can eliminate that theory:
it's still zero if I do the pg_terminate_backend() from another
session.

As a short-term fix, we could just go back to allowing the regex to
consider the match optional.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-15 16:23  Jacob Champion <jacob.champion@enterprisedb.com>
  parent: Andrew Dunstan <andrew@dunslane.net>
  0 siblings, 1 reply; 54+ messages in thread

From: Jacob Champion @ 2026-04-15 16:23 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Jakub Wartak <jakub.wartak@enterprisedb.com>; Chao Li <li.evan.chao@gmail.com>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Wed, Apr 15, 2026 at 7:17 AM Andrew Dunstan <andrew@dunslane.net> wrote:
> OK, pushed. Thanks.

I hit the following in the pg_basebackup tests just now, running on Linux:

    [08:41:21.621](0.377s) ok 196 - Walsender killed
    [09:09:11.134](1669.513s) # pump_until: timeout expired when
searching for "(?^:background process terminated unexpectedly)" with
stream: "pg_basebackup: error: unexpected termination of replication
stream: FATAL:  terminating connection due to administrator command
    # DETAIL:  Signal sent by PID 155573, UID 1000.
    # "
    [09:09:11.134](0.000s) not ok 197 - background process exit message
    [09:09:11.134](0.000s) #   Failed test 'background process exit message'
    #   at src/postgres/src/bin/pg_basebackup/t/010_pg_basebackup.pl line 1049.

But I haven't been able to reproduce since, so I don't know if this is
a new race, or the commit just exposed one that was there before?

Thanks,
--Jacob





^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-15 17:20  Andrew Dunstan <andrew@dunslane.net>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 54+ messages in thread

From: Andrew Dunstan @ 2026-04-15 17:20 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Jakub Wartak <jakub.wartak@enterprisedb.com>; Chao Li <li.evan.chao@gmail.com>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>


On 2026-04-15 We 12:04 PM, Tom Lane wrote:
> Andrew Dunstan <andrew@dunslane.net> writes:
>> On 2026-04-15 We 10:37 AM, Tom Lane wrote:
>>> The OpenBSD members of the buildfarm don't seem to like this.
>> Ugh.
>> I'm will take a look later today.
> I reproduced it locally on OpenBSD 7.7.  HAVE_SA_SIGINFO is defined,
> and the code to grab the pid/uid out of siginfo_t is definitely
> getting compiled.  As best I can tell, the kernel is simply passing
> zero for info->si_pid and si_uid.  This does not match up with the
> info available on the net, so I'm not sure what the issue is.
>
> Some googling suggested that on some platforms si_pid will be zero
> if the process signaled itself, but I can eliminate that theory:
> it's still zero if I do the pg_terminate_backend() from another
> session.
>
> As a short-term fix, we could just go back to allowing the regex to
> consider the match optional.
>
> 			


Ok, so we can get the buildfarm green I'll go and do that. But I think 
we should have an open item to tighten the test.


cheers


andrew


--
Andrew Dunstan
EDB: https://www.enterprisedb.com






^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-15 18:49  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Andrew Dunstan <andrew@dunslane.net>
  0 siblings, 2 replies; 54+ messages in thread

From: Tom Lane @ 2026-04-15 18:49 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Jakub Wartak <jakub.wartak@enterprisedb.com>; Chao Li <li.evan.chao@gmail.com>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

Andrew Dunstan <andrew@dunslane.net> writes:
> On 2026-04-15 We 12:04 PM, Tom Lane wrote:
>> As a short-term fix, we could just go back to allowing the regex to
>> consider the match optional.

> Ok, so we can get the buildfarm green I'll go and do that. But I think 
> we should have an open item to tighten the test.

I did some more digging, and got this from Google's AI Mode:

-----
openbsd does not fill siginfo_t si_pid for SIGTERM

On OpenBSD, si_pid is indeed not guaranteed to be filled for SIGTERM
(and many other signals), even when using SA_SIGINFO. This is a known
architectural behavior of the OpenBSD kernel rather than a bug. 

Why si_pid is zero or empty

Minimalist Kernel Design: Unlike Linux, which often populates si_pid
and si_uid for most user-sent signals, the OpenBSD kernel only
guarantees these fields for specific signals where they are
functionally required by POSIX, such as SIGCHLD.

Security & Information Leakage: OpenBSD has a history of limiting
information available across process boundaries to prevent
side-channel attacks or unnecessary information leaks about other
processes on the system [0.31].

Signal Queueing: Standard signals like SIGTERM are not "queued" with
data in the same way real-time signals (which OpenBSD does not fully
support in the same manner as Linux) would be.
-----

Now, none of the links it provided in support of these claims say
any such thing AFAICS, so maybe this is all an AI hallucination.
We could probably look into the OpenBSD kernel to check it, if we
were sufficiently motivated.  But I'm inclined to believe it and
just say "this info is not available on all platforms, even some
that HAVE_SA_SIGINFO".

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-15 19:39  Andrew Dunstan <andrew@dunslane.net>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 1 reply; 54+ messages in thread

From: Andrew Dunstan @ 2026-04-15 19:39 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Jakub Wartak <jakub.wartak@enterprisedb.com>; Chao Li <li.evan.chao@gmail.com>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>


On 2026-04-15 We 2:49 PM, Tom Lane wrote:
> Andrew Dunstan<andrew@dunslane.net> writes:
>> On 2026-04-15 We 12:04 PM, Tom Lane wrote:
>>> As a short-term fix, we could just go back to allowing the regex to
>>> consider the match optional.
>> Ok, so we can get the buildfarm green I'll go and do that. But I think
>> we should have an open item to tighten the test.
> I did some more digging, and got this from Google's AI Mode:
>
> -----
> openbsd does not fill siginfo_t si_pid for SIGTERM
>
> On OpenBSD, si_pid is indeed not guaranteed to be filled for SIGTERM
> (and many other signals), even when using SA_SIGINFO. This is a known
> architectural behavior of the OpenBSD kernel rather than a bug.
>
> Why si_pid is zero or empty
>
> Minimalist Kernel Design: Unlike Linux, which often populates si_pid
> and si_uid for most user-sent signals, the OpenBSD kernel only
> guarantees these fields for specific signals where they are
> functionally required by POSIX, such as SIGCHLD.
>
> Security & Information Leakage: OpenBSD has a history of limiting
> information available across process boundaries to prevent
> side-channel attacks or unnecessary information leaks about other
> processes on the system [0.31].
>
> Signal Queueing: Standard signals like SIGTERM are not "queued" with
> data in the same way real-time signals (which OpenBSD does not fully
> support in the same manner as Linux) would be.
> -----
>
> Now, none of the links it provided in support of these claims say
> any such thing AFAICS, so maybe this is all an AI hallucination.
> We could probably look into the OpenBSD kernel to check it, if we
> were sufficiently motivated.  But I'm inclined to believe it and
> just say "this info is not available on all platforms, even some
> that HAVE_SA_SIGINFO".
>
> 			



Thanks for looking into this. I guess we could make a test to see what 
the platform will support, but it seems like overkill. So now I'm just 
inclined to go back to making the line completely optional in the test 
and leave it at that.


cheers


andrew

--
Andrew Dunstan
EDB:https://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-16 05:50  Jakub Wartak <jakub.wartak@enterprisedb.com>
  parent: Jacob Champion <jacob.champion@enterprisedb.com>
  0 siblings, 0 replies; 54+ messages in thread

From: Jakub Wartak @ 2026-04-16 05:50 UTC (permalink / raw)
  To: Jacob Champion <jacob.champion@enterprisedb.com>; +Cc: Andrew Dunstan <andrew@dunslane.net>; Chao Li <li.evan.chao@gmail.com>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Wed, Apr 15, 2026 at 6:23 PM Jacob Champion
<jacob.champion@enterprisedb.com> wrote:
>
> On Wed, Apr 15, 2026 at 7:17 AM Andrew Dunstan <andrew@dunslane.net> wrote:
> > OK, pushed. Thanks.
>
> I hit the following in the pg_basebackup tests just now, running on Linux:
>
>     [08:41:21.621](0.377s) ok 196 - Walsender killed
>     [09:09:11.134](1669.513s) # pump_until: timeout expired when
> searching for "(?^:background process terminated unexpectedly)" with
> stream: "pg_basebackup: error: unexpected termination of replication
> stream: FATAL:  terminating connection due to administrator command
>     # DETAIL:  Signal sent by PID 155573, UID 1000.
>     # "
>     [09:09:11.134](0.000s) not ok 197 - background process exit message
>     [09:09:11.134](0.000s) #   Failed test 'background process exit message'
>     #   at src/postgres/src/bin/pg_basebackup/t/010_pg_basebackup.pl line 1049.
>
> But I haven't been able to reproduce since, so I don't know if this is
> a new race, or the commit just exposed one that was there before?

Hi Jacob, the time baseback took seems strange to me (27mins?!). It was
properly killed by a timeout, and the new code added the exact PID
that caused the issue.

If you happen to spot it again long running it might make some sense
to find where the time is spent there during that basebackup (in this
test we shouldn't be taking large backups).

Alternative would be to check pg server logs of that specific failed run
to see exactly where it was stuck after 08:41 (but before 09:09).

-J.





^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-16 06:08  Jakub Wartak <jakub.wartak@enterprisedb.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 0 replies; 54+ messages in thread

From: Jakub Wartak @ 2026-04-16 06:08 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Andrew Dunstan <andrew@dunslane.net>; Chao Li <li.evan.chao@gmail.com>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Wed, Apr 15, 2026 at 8:49 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> Andrew Dunstan <andrew@dunslane.net> writes:
> > On 2026-04-15 We 12:04 PM, Tom Lane wrote:
> >> As a short-term fix, we could just go back to allowing the regex to
> >> consider the match optional.
>
> > Ok, so we can get the buildfarm green I'll go and do that. But I think
> > we should have an open item to tighten the test.
>
> I did some more digging, and got this from Google's AI Mode:
>
> -----
> openbsd does not fill siginfo_t si_pid for SIGTERM
>
> On OpenBSD, si_pid is indeed not guaranteed to be filled for SIGTERM
> (and many other signals), even when using SA_SIGINFO. This is a known
> architectural behavior of the OpenBSD kernel rather than a bug.
>
> Why si_pid is zero or empty
>
> Minimalist Kernel Design: Unlike Linux, which often populates si_pid
> and si_uid for most user-sent signals, the OpenBSD kernel only
> guarantees these fields for specific signals where they are
> functionally required by POSIX, such as SIGCHLD.
>
> Security & Information Leakage: OpenBSD has a history of limiting
> information available across process boundaries to prevent
> side-channel attacks or unnecessary information leaks about other
> processes on the system [0.31].
>
> Signal Queueing: Standard signals like SIGTERM are not "queued" with
> data in the same way real-time signals (which OpenBSD does not fully
> support in the same manner as Linux) would be.
> -----
>
> Now, none of the links it provided in support of these claims say
> any such thing AFAICS, so maybe this is all an AI hallucination.
> We could probably look into the OpenBSD kernel to check it, if we
> were sufficiently motivated.  But I'm inclined to believe it and
> just say "this info is not available on all platforms, even some
> that HAVE_SA_SIGINFO".

Hi Tom,

It seems to be not a hallucination: it appears that they do initsiginfo() [1]
which zeros out struct siginfo_t without setting si_pid there. The
only reference about si_pid is that their waitid(2) fills it properly
and that's visibile in their dowait*() kernel-side implementation
too.

-J.

[1] - https://github.com/openbsd/src/blob/master/sys/kern/kern_sig.c#L2166





^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-16 06:09  Jakub Wartak <jakub.wartak@enterprisedb.com>
  parent: Andrew Dunstan <andrew@dunslane.net>
  0 siblings, 1 reply; 54+ messages in thread

From: Jakub Wartak @ 2026-04-16 06:09 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Chao Li <li.evan.chao@gmail.com>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Wed, Apr 15, 2026 at 9:39 PM Andrew Dunstan <andrew@dunslane.net> wrote:
>
>
> On 2026-04-15 We 2:49 PM, Tom Lane wrote:
>
> Andrew Dunstan <andrew@dunslane.net> writes:
>
> On 2026-04-15 We 12:04 PM, Tom Lane wrote:
>
> As a short-term fix, we could just go back to allowing the regex to
> consider the match optional.
>
> Ok, so we can get the buildfarm green I'll go and do that. But I think
> we should have an open item to tighten the test.
>
> I did some more digging, and got this from Google's AI Mode:
>
> -----
> openbsd does not fill siginfo_t si_pid for SIGTERM
>
> On OpenBSD, si_pid is indeed not guaranteed to be filled for SIGTERM
> (and many other signals), even when using SA_SIGINFO. This is a known
> architectural behavior of the OpenBSD kernel rather than a bug.
>
> Why si_pid is zero or empty
>
> Minimalist Kernel Design: Unlike Linux, which often populates si_pid
> and si_uid for most user-sent signals, the OpenBSD kernel only
> guarantees these fields for specific signals where they are
> functionally required by POSIX, such as SIGCHLD.
>
> Security & Information Leakage: OpenBSD has a history of limiting
> information available across process boundaries to prevent
> side-channel attacks or unnecessary information leaks about other
> processes on the system [0.31].
>
> Signal Queueing: Standard signals like SIGTERM are not "queued" with
> data in the same way real-time signals (which OpenBSD does not fully
> support in the same manner as Linux) would be.
> -----
>
> Now, none of the links it provided in support of these claims say
> any such thing AFAICS, so maybe this is all an AI hallucination.
> We could probably look into the OpenBSD kernel to check it, if we
> were sufficiently motivated.  But I'm inclined to believe it and
> just say "this info is not available on all platforms, even some
> that HAVE_SA_SIGINFO".
>
>
>
>
>
> Thanks for looking into this. I guess we could make a test to see what the platform will support, but it seems like overkill. So now I'm just inclined to go back to making the line completely optional in the test and leave it at that.
>

+1

-J.





^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-16 08:34  Jakub Wartak <jakub.wartak@enterprisedb.com>
  parent: Jakub Wartak <jakub.wartak@enterprisedb.com>
  0 siblings, 1 reply; 54+ messages in thread

From: Jakub Wartak @ 2026-04-16 08:34 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Chao Li <li.evan.chao@gmail.com>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Thu, Apr 16, 2026 at 8:09 AM Jakub Wartak
<jakub.wartak@enterprisedb.com> wrote:
>
> On Wed, Apr 15, 2026 at 9:39 PM Andrew Dunstan <andrew@dunslane.net> wrote:
> >
> >
> > On 2026-04-15 We 2:49 PM, Tom Lane wrote:
> >
> > Andrew Dunstan <andrew@dunslane.net> writes:
> >
> > On 2026-04-15 We 12:04 PM, Tom Lane wrote:
> >
> > As a short-term fix, we could just go back to allowing the regex to
> > consider the match optional.
> >
> > Ok, so we can get the buildfarm green I'll go and do that. But I think
> > we should have an open item to tighten the test.
> >
> > I did some more digging, and got this from Google's AI Mode:
> >
> > -----
> > openbsd does not fill siginfo_t si_pid for SIGTERM
> >
> > On OpenBSD, si_pid is indeed not guaranteed to be filled for SIGTERM
> > (and many other signals), even when using SA_SIGINFO. This is a known
> > architectural behavior of the OpenBSD kernel rather than a bug.
> >
> > Why si_pid is zero or empty
> >
> > Minimalist Kernel Design: Unlike Linux, which often populates si_pid
> > and si_uid for most user-sent signals, the OpenBSD kernel only
> > guarantees these fields for specific signals where they are
> > functionally required by POSIX, such as SIGCHLD.
> >
> > Security & Information Leakage: OpenBSD has a history of limiting
> > information available across process boundaries to prevent
> > side-channel attacks or unnecessary information leaks about other
> > processes on the system [0.31].
> >
> > Signal Queueing: Standard signals like SIGTERM are not "queued" with
> > data in the same way real-time signals (which OpenBSD does not fully
> > support in the same manner as Linux) would be.
> > -----
> >
> > Now, none of the links it provided in support of these claims say
> > any such thing AFAICS, so maybe this is all an AI hallucination.
> > We could probably look into the OpenBSD kernel to check it, if we
> > were sufficiently motivated.  But I'm inclined to believe it and
> > just say "this info is not available on all platforms, even some
> > that HAVE_SA_SIGINFO".
> >
> >
> >
> >
> >
> > Thanks for looking into this. I guess we could make a test to see what the platform will support, but it seems like overkill. So now I'm just inclined to go back to making the line completely optional in the test and leave it at that.
> >
>
> +1

And here is the patch for that.


-J.

Attachments:

  [application/x-patch] v1-0001-Fix-test-about-the-lack-of-the-errdetail-signal-i.patch (1.9K, ../../CAKZiRmzSpX4C=3ou8VUJqX-RfQ+rNc9uw_Fn5gfD8NVctR4B3w@mail.gmail.com/2-v1-0001-Fix-test-about-the-lack-of-the-errdetail-signal-i.patch)
  download | inline diff:
From 8f5ef144acf5f15c132df655fd6f566f7d0d3233 Mon Sep 17 00:00:00 2001
From: Jakub Wartak <jakub.wartak@enterprisedb.com>
Date: Thu, 16 Apr 2026 10:00:40 +0200
Subject: [PATCH v1] Fix test about the lack of the errdetail() signal info
 about PID/UIDs on OpenBSD.

Commit 3e2a1496bae6 made the psql TAP test require the DETAIL line on
platforms with SA_SIGINFO, rather than making it optional. This unexpectly
blowed up on OpenBSD buildfarm members, because OpenBSD is not setting si_pid
properly for SIGTERM signals even while having SA_SIGINFO defined.

Make the DETAIL line optional as it was in 55890a919454.

Author: Jakub Wartak <jakub.wartak@enterprisedb.com>
Suggested-by: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Andrew Dunstan <andrew@dunslane.net>
Discussion: https://www.postgresql.org/message-id/2007157.1776269052%40sss.pgh.pa.us
---
 src/bin/psql/t/001_basic.pl | 5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)

diff --git a/src/bin/psql/t/001_basic.pl b/src/bin/psql/t/001_basic.pl
index 9d966c7bece..7c21204c1f2 100644
--- a/src/bin/psql/t/001_basic.pl
+++ b/src/bin/psql/t/001_basic.pl
@@ -142,11 +142,8 @@ my ($ret, $out, $err) = $node->psql('postgres',
 is($ret, 2, 'server crash: psql exit code');
 like($out, qr/before/, 'server crash: output before crash');
 unlike($out, qr/AFTER/, 'server crash: no output after crash');
-my $detail_re = check_pg_config("#define HAVE_SA_SIGINFO 1")
-	? qr/DETAIL:  Signal sent by PID \d+, UID \d+\.\n/
-	: qr//;
 like( $err, qr/psql:<stdin>:2: FATAL:  terminating connection due to administrator command
-${detail_re}psql:<stdin>:2: server closed the connection unexpectedly
+(?:DETAIL:  Signal sent by PID \d+, UID \d+\.\n)?psql:<stdin>:2: server closed the connection unexpectedly
 	This probably means the server terminated abnormally
 	before or while processing the request.
 psql:<stdin>:2: error: connection to server was lost/,
-- 
2.43.0



^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-16 20:58  Andrew Dunstan <andrew@dunslane.net>
  parent: Jakub Wartak <jakub.wartak@enterprisedb.com>
  0 siblings, 1 reply; 54+ messages in thread

From: Andrew Dunstan @ 2026-04-16 20:58 UTC (permalink / raw)
  To: Jakub Wartak <jakub.wartak@enterprisedb.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Chao Li <li.evan.chao@gmail.com>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>


On 2026-04-16 Th 4:34 AM, Jakub Wartak wrote:
> On Thu, Apr 16, 2026 at 8:09 AM Jakub Wartak
> <jakub.wartak@enterprisedb.com> wrote:
>> On Wed, Apr 15, 2026 at 9:39 PM Andrew Dunstan<andrew@dunslane.net> wrote:
>>>
>>> On 2026-04-15 We 2:49 PM, Tom Lane wrote:
>>>
>>> Andrew Dunstan<andrew@dunslane.net> writes:
>>>
>>> On 2026-04-15 We 12:04 PM, Tom Lane wrote:
>>>
>>> As a short-term fix, we could just go back to allowing the regex to
>>> consider the match optional.
>>>
>>> Ok, so we can get the buildfarm green I'll go and do that. But I think
>>> we should have an open item to tighten the test.
>>>
>>> I did some more digging, and got this from Google's AI Mode:
>>>
>>> -----
>>> openbsd does not fill siginfo_t si_pid for SIGTERM
>>>
>>> On OpenBSD, si_pid is indeed not guaranteed to be filled for SIGTERM
>>> (and many other signals), even when using SA_SIGINFO. This is a known
>>> architectural behavior of the OpenBSD kernel rather than a bug.
>>>
>>> Why si_pid is zero or empty
>>>
>>> Minimalist Kernel Design: Unlike Linux, which often populates si_pid
>>> and si_uid for most user-sent signals, the OpenBSD kernel only
>>> guarantees these fields for specific signals where they are
>>> functionally required by POSIX, such as SIGCHLD.
>>>
>>> Security & Information Leakage: OpenBSD has a history of limiting
>>> information available across process boundaries to prevent
>>> side-channel attacks or unnecessary information leaks about other
>>> processes on the system [0.31].
>>>
>>> Signal Queueing: Standard signals like SIGTERM are not "queued" with
>>> data in the same way real-time signals (which OpenBSD does not fully
>>> support in the same manner as Linux) would be.
>>> -----
>>>
>>> Now, none of the links it provided in support of these claims say
>>> any such thing AFAICS, so maybe this is all an AI hallucination.
>>> We could probably look into the OpenBSD kernel to check it, if we
>>> were sufficiently motivated.  But I'm inclined to believe it and
>>> just say "this info is not available on all platforms, even some
>>> that HAVE_SA_SIGINFO".
>>>
>>>
>>>
>>>
>>>
>>> Thanks for looking into this. I guess we could make a test to see what the platform will support, but it seems like overkill. So now I'm just inclined to go back to making the line completely optional in the test and leave it at that.
>>>
>> +1
> And here is the patch for that.
>
>


Thanks, I have pushed the fix.


cheers


andrew

--
Andrew Dunstan
EDB:https://www.enterprisedb.com

^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-23 09:27  Chao Li <li.evan.chao@gmail.com>
  parent: Andrew Dunstan <andrew@dunslane.net>
  0 siblings, 1 reply; 54+ messages in thread

From: Chao Li @ 2026-04-23 09:27 UTC (permalink / raw)
  To: Andrew Dunstan <andrew@dunslane.net>; +Cc: Jakub Wartak <jakub.wartak@enterprisedb.com>; Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>



> On Apr 17, 2026, at 04:58, Andrew Dunstan <andrew@dunslane.net> wrote:
> 
> 
> On 2026-04-16 Th 4:34 AM, Jakub Wartak wrote:
>> On Thu, Apr 16, 2026 at 8:09 AM Jakub Wartak
>> <jakub.wartak@enterprisedb.com> wrote:
>> 
>>> On Wed, Apr 15, 2026 at 9:39 PM Andrew Dunstan <andrew@dunslane.net> wrote:
>>> 
>>>> 
>>>> On 2026-04-15 We 2:49 PM, Tom Lane wrote:
>>>> 
>>>> Andrew Dunstan <andrew@dunslane.net> writes:
>>>> 
>>>> On 2026-04-15 We 12:04 PM, Tom Lane wrote:
>>>> 
>>>> As a short-term fix, we could just go back to allowing the regex to
>>>> consider the match optional.
>>>> 
>>>> Ok, so we can get the buildfarm green I'll go and do that. But I think
>>>> we should have an open item to tighten the test.
>>>> 
>>>> I did some more digging, and got this from Google's AI Mode:
>>>> 
>>>> -----
>>>> openbsd does not fill siginfo_t si_pid for SIGTERM
>>>> 
>>>> On OpenBSD, si_pid is indeed not guaranteed to be filled for SIGTERM
>>>> (and many other signals), even when using SA_SIGINFO. This is a known
>>>> architectural behavior of the OpenBSD kernel rather than a bug.
>>>> 
>>>> Why si_pid is zero or empty
>>>> 
>>>> Minimalist Kernel Design: Unlike Linux, which often populates si_pid
>>>> and si_uid for most user-sent signals, the OpenBSD kernel only
>>>> guarantees these fields for specific signals where they are
>>>> functionally required by POSIX, such as SIGCHLD.
>>>> 
>>>> Security & Information Leakage: OpenBSD has a history of limiting
>>>> information available across process boundaries to prevent
>>>> side-channel attacks or unnecessary information leaks about other
>>>> processes on the system [0.31].
>>>> 
>>>> Signal Queueing: Standard signals like SIGTERM are not "queued" with
>>>> data in the same way real-time signals (which OpenBSD does not fully
>>>> support in the same manner as Linux) would be.
>>>> -----
>>>> 
>>>> Now, none of the links it provided in support of these claims say
>>>> any such thing AFAICS, so maybe this is all an AI hallucination.
>>>> We could probably look into the OpenBSD kernel to check it, if we
>>>> were sufficiently motivated. But I'm inclined to believe it and
>>>> just say "this info is not available on all platforms, even some
>>>> that HAVE_SA_SIGINFO".
>>>> 
>>>> 
>>>> 
>>>> 
>>>> 
>>>> Thanks for looking into this. I guess we could make a test to see what the platform will support, but it seems like overkill. So now I'm just inclined to go back to making the line completely optional in the test and leave it at that.
>>>> 
>>>> 
>>> +1
>>> 
>> And here is the patch for that.
>> 
>> 
>> 
> 
> 
> Thanks, I have pushed the fix.
> 
> cheers
> 
> andrew --
> Andrew Dunstan
> EDB: https://www.enterprisedb.com
> 

I just got a suspicion about this feature. The repro is very simple: let a normal user connect to the server, then run pg_ctl stop, and from psql you get:
```
evantest=> select 1;
FATAL:  terminating connection due to administrator command
DETAIL:  Signal sent by PID 17523, UID 501.
server closed the connection unexpectedly
	This probably means the server terminated abnormally
	before or while processing the request.
The connection to the server was lost. Attempting reset: Failed.
The connection to the server was lost. Attempting reset: Failed.
!?>
```

Do we really need to show the DETAIL message with the PID and UID to an ordinary client? Is there any concern about leaking the UID in a shared production deployment?

If this is confirmed an issue, I made a simple fix by using errdetail_log() to only emit the detail message to server log. Please the attached diff file.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/

Attachments:

  [application/octet-stream] not_emit_pid_uid_to_client.diff (2.8K, ../../E5CA274C-74BD-4067-8B73-A3AD8C080EFA@gmail.com/2-not_emit_pid_uid_to_client.diff)
  download | inline diff:
diff --git a/src/backend/replication/syncrep.c b/src/backend/replication/syncrep.c
index 73450fe437e..e0e30579c59 100644
--- a/src/backend/replication/syncrep.c
+++ b/src/backend/replication/syncrep.c
@@ -304,9 +304,10 @@ SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
 				ereport(WARNING,
 						(errcode(ERRCODE_ADMIN_SHUTDOWN),
 						 errmsg("canceling the wait for synchronous replication and terminating connection due to administrator command"),
-						 errdetail("The transaction has already committed locally, but might not have been replicated to the standby.  Signal sent by PID %d, UID %d.",
-								   (int) ProcDieSenderPid,
-								   (int) ProcDieSenderUid)));
+						 errdetail("The transaction has already committed locally, but might not have been replicated to the standby."),
+						 errdetail_log("The transaction has already committed locally, but might not have been replicated to the standby.  Signal sent by PID %d, UID %d.",
+									   (int) ProcDieSenderPid,
+									   (int) ProcDieSenderUid)));
 			else
 				ereport(WARNING,
 						(errcode(ERRCODE_ADMIN_SHUTDOWN),
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 2c1f14b7889..dbef734a93f 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -111,12 +111,13 @@ int			client_connection_check_interval = 0;
 int			restrict_nonsystem_relation_kind;
 
 /*
- * Include signal sender PID/UID as errdetail when available (SA_SIGINFO).
- * The caller must supply the (already-captured) pid and uid values.
+ * Include signal sender PID/UID in the server log when available
+ * (SA_SIGINFO). The caller must supply the already-captured pid and uid
+ * values.
  */
 #define ERRDETAIL_SIGNAL_SENDER(pid, uid) \
 	((pid) == 0 ? 0 : \
-	 errdetail("Signal sent by PID %d, UID %d.", (int) (pid), (int) (uid)))
+	 errdetail_log("Signal sent by PID %d, UID %d.", (int) (pid), (int) (uid)))
 
 /* ----------------
  *		private typedefs etc
diff --git a/src/bin/psql/t/001_basic.pl b/src/bin/psql/t/001_basic.pl
index 7c21204c1f2..ed8c2e939b0 100644
--- a/src/bin/psql/t/001_basic.pl
+++ b/src/bin/psql/t/001_basic.pl
@@ -143,11 +143,11 @@ is($ret, 2, 'server crash: psql exit code');
 like($out, qr/before/, 'server crash: output before crash');
 unlike($out, qr/AFTER/, 'server crash: no output after crash');
 like( $err, qr/psql:<stdin>:2: FATAL:  terminating connection due to administrator command
-(?:DETAIL:  Signal sent by PID \d+, UID \d+\.\n)?psql:<stdin>:2: server closed the connection unexpectedly
+psql:<stdin>:2: server closed the connection unexpectedly
 	This probably means the server terminated abnormally
 	before or while processing the request.
 psql:<stdin>:2: error: connection to server was lost/,
-	'server crash: error message');
+		'server crash: error message');
 
 # test \errverbose
 #

^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-04-23 10:20  Jakub Wartak <jakub.wartak@enterprisedb.com>
  parent: Chao Li <li.evan.chao@gmail.com>
  0 siblings, 1 reply; 54+ messages in thread

From: Jakub Wartak @ 2026-04-23 10:20 UTC (permalink / raw)
  To: Chao Li <li.evan.chao@gmail.com>; +Cc: Andrew Dunstan <andrew@dunslane.net>; Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Thu, Apr 23, 2026 at 11:28 AM Chao Li <li.evan.chao@gmail.com> wrote:

Hi Chao

>
> I just got a suspicion about this feature. The repro is very simple: let a normal user connect to the server, then run pg_ctl stop, and from psql you get:
> ```
> evantest=> select 1;
> FATAL:  terminating connection due to administrator command
> DETAIL:  Signal sent by PID 17523, UID 501.
> server closed the connection unexpectedly
>         This probably means the server terminated abnormally
>         before or while processing the request.
> The connection to the server was lost. Attempting reset: Failed.
> The connection to the server was lost. Attempting reset: Failed.
> !?>
> ```
>
> Do we really need to show the DETAIL message with the PID and UID to an ordinary client? Is there any concern about leaking the UID in a shared production deployment?
>
> If this is confirmed an issue, I made a simple fix by using errdetail_log() to only emit the detail message to server log. Please the attached diff file.

+1, I think logging just to file is even better than sending it to the
client(s) and it also solves the potential security risk (if any).

-J.





^ permalink  raw  reply  [nested|flat] 54+ messages in thread

* Re: Add errdetail() with PID and UID about source of termination signal
@ 2026-05-01 17:26  Andrew Dunstan <andrew@dunslane.net>
  parent: Jakub Wartak <jakub.wartak@enterprisedb.com>
  0 siblings, 0 replies; 54+ messages in thread

From: Andrew Dunstan @ 2026-05-01 17:26 UTC (permalink / raw)
  To: Jakub Wartak <jakub.wartak@enterprisedb.com>; +Cc: Chao Li <li.evan.chao@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Jim Jones <jim.jones@uni-muenster.de>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>

On Thu, Apr 23, 2026 at 6:20 AM Jakub Wartak <jakub.wartak@enterprisedb.com>
wrote:

> On Thu, Apr 23, 2026 at 11:28 AM Chao Li <li.evan.chao@gmail.com> wrote:
>
> Hi Chao
>
> >
> > I just got a suspicion about this feature. The repro is very simple: let
> a normal user connect to the server, then run pg_ctl stop, and from psql
> you get:
> > ```
> > evantest=> select 1;
> > FATAL:  terminating connection due to administrator command
> > DETAIL:  Signal sent by PID 17523, UID 501.
> > server closed the connection unexpectedly
> >         This probably means the server terminated abnormally
> >         before or while processing the request.
> > The connection to the server was lost. Attempting reset: Failed.
> > The connection to the server was lost. Attempting reset: Failed.
> > !?>
> > ```
> >
> > Do we really need to show the DETAIL message with the PID and UID to an
> ordinary client? Is there any concern about leaking the UID in a shared
> production deployment?
> >
> > If this is confirmed an issue, I made a simple fix by using
> errdetail_log() to only emit the detail message to server log. Please the
> attached diff file.
>
> +1, I think logging just to file is even better than sending it to the
> client(s) and it also solves the potential security risk (if any).
>
>
> I agree, I have pushed the patch.

cheers

andrew

^ permalink  raw  reply  [nested|flat] 54+ messages in thread


end of thread, other threads:[~2026-05-01 17:26 UTC | newest]

Thread overview: 54+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-02-18 07:32 Add errdetail() with PID and UID about source of termination signal Jakub Wartak <jakub.wartak@enterprisedb.com>
2026-02-18 16:08 ` Jim Jones <jim.jones@uni-muenster.de>
2026-02-23 13:28   ` Jakub Wartak <jakub.wartak@enterprisedb.com>
2026-02-24 08:39     ` Chao Li <li.evan.chao@gmail.com>
2026-02-24 10:05       ` Jakub Wartak <jakub.wartak@enterprisedb.com>
2026-02-24 16:15         ` Andrew Dunstan <andrew@dunslane.net>
2026-02-25 08:26           ` Jakub Wartak <jakub.wartak@enterprisedb.com>
2026-02-25 09:15             ` Chao Li <li.evan.chao@gmail.com>
2026-02-25 10:45               ` Jakub Wartak <jakub.wartak@enterprisedb.com>
2026-02-26 03:08                 ` Chao Li <li.evan.chao@gmail.com>
2026-02-26 09:25                   ` Jakub Wartak <jakub.wartak@enterprisedb.com>
2026-04-06 16:51                     ` Andrew Dunstan <andrew@dunslane.net>
2026-04-06 19:36                       ` Daniel Gustafsson <daniel@yesql.se>
2026-04-07 03:55                       ` jie wang <jugierwang@gmail.com>
2026-04-07 09:10                         ` Jakub Wartak <jakub.wartak@enterprisedb.com>
2026-04-07 14:36                           ` Andrew Dunstan <andrew@dunslane.net>
2026-04-07 14:55                       ` Andres Freund <andres@anarazel.de>
2026-04-07 16:49                         ` Andrew Dunstan <andrew@dunslane.net>
2026-04-07 18:19                           ` Andres Freund <andres@anarazel.de>
2026-04-07 21:31                             ` Andrew Dunstan <andrew@dunslane.net>
2026-04-07 22:56                               ` Andres Freund <andres@anarazel.de>
2026-04-08 01:03                                 ` Chao Li <li.evan.chao@gmail.com>
2026-04-08 09:13                                   ` Jim Jones <jim.jones@uni-muenster.de>
2026-04-08 17:01                                     ` Andres Freund <andres@anarazel.de>
2026-04-09 03:11                                       ` Chao Li <li.evan.chao@gmail.com>
2026-04-09 06:14                                         ` Chao Li <li.evan.chao@gmail.com>
2026-04-09 14:47                                           ` Andres Freund <andres@anarazel.de>
2026-04-10 06:18                                             ` Chao Li <li.evan.chao@gmail.com>
2026-04-09 10:59                                       ` Andrew Dunstan <andrew@dunslane.net>
2026-04-09 14:00                                         ` Andres Freund <andres@anarazel.de>
2026-04-10 07:40                                         ` Chao Li <li.evan.chao@gmail.com>
2026-04-14 10:40                                           ` Jakub Wartak <jakub.wartak@enterprisedb.com>
2026-04-14 20:38                                             ` Andrew Dunstan <andrew@dunslane.net>
2026-04-15 06:11                                               ` Chao Li <li.evan.chao@gmail.com>
2026-04-15 11:45                                                 ` Kirill Reshke <reshkekirill@gmail.com>
2026-04-15 12:14                                                   ` Andrew Dunstan <andrew@dunslane.net>
2026-04-15 12:45                                                     ` Kirill Reshke <reshkekirill@gmail.com>
2026-04-15 09:27                                               ` Jakub Wartak <jakub.wartak@enterprisedb.com>
2026-04-15 11:37                                                 ` Andrew Dunstan <andrew@dunslane.net>
2026-04-15 16:23                                                   ` Jacob Champion <jacob.champion@enterprisedb.com>
2026-04-16 05:50                                                     ` Jakub Wartak <jakub.wartak@enterprisedb.com>
2026-04-15 14:37                                                 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-04-15 15:26                                                   ` Andrew Dunstan <andrew@dunslane.net>
2026-04-15 16:04                                                   ` Tom Lane <tgl@sss.pgh.pa.us>
2026-04-15 17:20                                                     ` Andrew Dunstan <andrew@dunslane.net>
2026-04-15 18:49                                                       ` Tom Lane <tgl@sss.pgh.pa.us>
2026-04-15 19:39                                                         ` Andrew Dunstan <andrew@dunslane.net>
2026-04-16 06:09                                                           ` Jakub Wartak <jakub.wartak@enterprisedb.com>
2026-04-16 08:34                                                             ` Jakub Wartak <jakub.wartak@enterprisedb.com>
2026-04-16 20:58                                                               ` Andrew Dunstan <andrew@dunslane.net>
2026-04-23 09:27                                                                 ` Chao Li <li.evan.chao@gmail.com>
2026-04-23 10:20                                                                   ` Jakub Wartak <jakub.wartak@enterprisedb.com>
2026-05-01 17:26                                                                     ` Andrew Dunstan <andrew@dunslane.net>
2026-04-16 06:08                                                         ` Jakub Wartak <jakub.wartak@enterprisedb.com>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox