--- postgresql-9.5.1/src/bin/psql/input.c	2016-02-08 21:12:28.000000000 +0000
+++ postgresql-9.5.1-gw/src/bin/psql/input.c	2018-01-16 11:38:08.000000000 +0000
@@ -12,6 +12,8 @@
 #endif
 #include <fcntl.h>
 #include <limits.h>
+#include <signal.h>
+#include <stdlib.h>
 
 #include "input.h"
 #include "settings.h"
@@ -47,7 +49,19 @@
 #endif
 
 static void finishInput(void);
-
+static char *readline_buff=NULL;
+static int readline_running=0;
+static int sigwinch_received=0;
+static void cb_linehandler (char *line)
+{
+	readline_running=0;
+	readline_buff=line;
+}
+static void
+sighandler (int sig)
+{
+	sigwinch_received = 1;
+}
 
 /*
  * gets_interactive()
@@ -80,10 +94,55 @@
 		sigint_interrupt_enabled = true;
 
 		/* On some platforms, readline is declared as readline(char *) */
-		result = readline((char *) prompt);
+/* alternative readline version to intercept ctrl-d */
+		{
+			fd_set fds;
+			int r;
+
+			signal (SIGWINCH, sighandler);
+
+			rl_callback_handler_install (prompt, cb_linehandler);
+
+			readline_running = 1;
+			while (readline_running)
+			{
+				FD_ZERO (&fds);
+				FD_SET (fileno (rl_instream), &fds);    
+
+				r = select (fileno(rl_instream)+1, &fds, NULL, NULL, NULL);
+				if (r < 0 && errno != EINTR)
+				{
+					perror ("rltest: select");
+					rl_callback_handler_remove ();
+					break;
+				}
+				if (sigwinch_received)
+				{
+					rl_resize_terminal ();
+					sigwinch_received = 0;
+				}
+				if (r < 0) continue;     
 
+				if (FD_ISSET (fileno (rl_instream), &fds)) 
+				{
+					unsigned char c;
+					if (read(fileno(rl_instream), &c, 1) && c == 4)  /* if we get ctrl-D, wipe the existing buffer */
+					{
+						rl_replace_line("\\q", 0); /* put in our exit command */
+						c='\n'; /* and make this the char we're going to send */
+					}
+					if (c > 0) 
+					{
+						rl_stuff_char(c);
+						rl_callback_read_char ();
+					}
+				}
+			}
+			result=readline_buff;
+		}
 		/* Disable SIGINT again */
 		sigint_interrupt_enabled = false;
+		rl_callback_handler_remove ();
 
 		return result;
 	}
