From a290e1635b8b0a5d4c60b0bdc280684b0b394cd6 Mon Sep 17 00:00:00 2001
From: Jelte Fennema-Nio <postgres@jeltef.nl>
Date: Sat, 7 Mar 2026 00:05:05 +0100
Subject: [PATCH v5 5/5] fixup! Don't use deprecated and insecure PQcancel psql
 and other tools anymore

Drain the pipe in the cancel thread.
---
 src/fe_utils/cancel.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)

diff --git a/src/fe_utils/cancel.c b/src/fe_utils/cancel.c
index caaf3e7c675..a5607b204cc 100644
--- a/src/fe_utils/cancel.c
+++ b/src/fe_utils/cancel.c
@@ -305,7 +305,7 @@ cancel_thread_main(void *arg)
 		char		buf[16];
 		ssize_t		rc;
 
-		/* Wait for signal handler to wake us up */
+		/* Wait for signal handler to wake us up (blocking read) */
 		rc = read(cancel_pipe[0], buf, sizeof(buf));
 		if (rc <= 0)
 		{
@@ -315,6 +315,14 @@ cancel_thread_main(void *arg)
 			break;
 		}
 
+		/* Drain the pipe so multiple SIGINTs don't queue up extra wakeups */
+		fcntl(cancel_pipe[0], F_SETFL, O_NONBLOCK);
+		while (read(cancel_pipe[0], buf, sizeof(buf)) > 0)
+		{
+			/* loop until pipe is drained */
+		}
+		fcntl(cancel_pipe[0], F_SETFL, 0);
+
 		SendCancelRequest();
 	}
 
-- 
2.53.0

