From e916400c69168a4e27cd41910770f48a6a7b41af Mon Sep 17 00:00:00 2001
From: Stepan Neretin <slpmcf@gmail.com>
Date: Mon, 23 Nov 2026 22:56:42 +0700
Subject: [PATCH 2/3] Add persistent archive_command protocol.

With archive_command_persistent on, start one long-lived helper and feed
it files over stdin instead of calling system() per file.  It answers
ok, retry, or fail.  No %f/%p in this mode, Unix only for now, and a
mode or command change restarts the archiver so the helper is rebuilt.

Discussion: https://postgr.es/m/CA+Yyo5TfMpUE3s=WKrWcaYbBWbO2VNyRnRt_5hy-VPrMhjXVWg@mail.gmail.com
---
 src/backend/access/transam/xlog.c             |  19 +
 src/backend/archive/shell_archive.c           | 692 +++++++++++++++++-
 src/backend/postmaster/pgarch.c               |  36 +
 src/backend/utils/misc/guc_parameters.dat     |  10 +-
 src/backend/utils/misc/postgresql.conf.sample |   1 +
 src/include/access/xlog.h                     |   1 +
 src/include/utils/guc_hooks.h                 |   2 +
 7 files changed, 752 insertions(+), 9 deletions(-)

diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 9419325..aba7892 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -125,6 +125,7 @@ int			XLOGbuffers = -1;
 int			XLogArchiveTimeout = 0;
 int			XLogArchiveMode = ARCHIVE_MODE_OFF;
 char	   *XLogArchiveCommand = NULL;
+bool		XLogArchiveCommandPersistent = false;
 int			XLogArchiveAsyncMax = 8;
 bool		EnableHotStandby = false;
 bool		fullPageWrites = true;
@@ -5447,6 +5448,24 @@ show_archive_command(void)
 		return "(disabled)";
 }
 
+bool
+check_archive_command_persistent(bool *newval, void **extra, GucSource source)
+{
+#ifdef WIN32
+	if (*newval)
+	{
+		GUC_check_errcode(ERRCODE_FEATURE_NOT_SUPPORTED);
+		GUC_check_errmsg("\"archive_command_persistent\" is not supported on Windows");
+		return false;
+	}
+#else
+	(void) newval;
+#endif
+	(void) extra;
+	(void) source;
+	return true;
+}
+
 /*
  * GUC show_hook for in_hot_standby
  */
diff --git a/src/backend/archive/shell_archive.c b/src/backend/archive/shell_archive.c
index 0b427a6..f53d7bc 100644
--- a/src/backend/archive/shell_archive.c
+++ b/src/backend/archive/shell_archive.c
@@ -15,43 +15,122 @@
  */
 #include "postgres.h"
 
+#include <fcntl.h>
+#include <signal.h>
 #include <sys/wait.h>
+#include <unistd.h>
 
 #include "access/xlog.h"
+#include "access/xlog_internal.h"
 #include "archive/archive_module.h"
 #include "archive/shell_archive.h"
 #include "common/percentrepl.h"
+#include "libpq/pqsignal.h"
+#include "miscadmin.h"
 #include "pgstat.h"
+#ifndef WIN32
+#include "postmaster/fork_process.h"
+#endif
+#include "storage/ipc.h"
+#include "storage/latch.h"
+#include "utils/timestamp.h"
 #include "utils/wait_event.h"
 
+/* Must match archive_async_max GUC max. */
+#define SHELL_OUTSTANDING_MAX	64
+
 static bool shell_archive_configured(ArchiveModuleState *state);
 static bool shell_archive_file(ArchiveModuleState *state,
 							   const char *file,
 							   const char *path);
 static void shell_archive_shutdown(ArchiveModuleState *state);
 
-static const ArchiveModuleCallbacks shell_archive_callbacks = {
-	.startup_cb = NULL,
+#ifndef WIN32
+static bool shell_archive_submit(ArchiveModuleState *state,
+								 const char *file,
+								 const char *path);
+static bool shell_archive_poll(ArchiveModuleState *state,
+							   const char **file,
+							   ArchiveResultStatus *status,
+							   long timeout_ms);
+static void shell_archive_cancel(ArchiveModuleState *state);
+
+static void shell_sigchld_handler(SIGNAL_ARGS);
+static void shell_prepare_child(void);
+static bool shell_command_has_file_placeholders(const char *cmd);
+static void shell_reset_child(void);
+static void shell_kill_child(void);
+static bool shell_child_alive(void);
+static bool shell_ensure_child(void);
+static bool shell_spawn_child(void);
+static int shell_write_line(const char *line);
+static bool shell_read_line(char *buf, size_t buflen, long timeout_ms);
+static bool shell_outstanding_add(const char *file);
+static bool shell_outstanding_remove(const char *file);
+static void shell_fail_outstanding(void);
+static bool shell_take_retry(const char **file, ArchiveResultStatus *status);
+static bool shell_parse_result(const char *line, char *file, size_t filelen,
+							   ArchiveResultStatus *status);
+#endif
+
+static const ArchiveModuleCallbacks shell_archive_sync_callbacks = {
 	.check_configured_cb = shell_archive_configured,
 	.archive_file_cb = shell_archive_file,
 	.shutdown_cb = shell_archive_shutdown
 };
 
+#ifndef WIN32
+static const ArchiveModuleCallbacks shell_archive_async_callbacks = {
+	.check_configured_cb = shell_archive_configured,
+	.shutdown_cb = shell_archive_shutdown,
+	.submit_cb = shell_archive_submit,
+	.poll_cb = shell_archive_poll,
+	.cancel_cb = shell_archive_cancel
+};
+
+static pid_t shell_child_pid = 0;
+static int	shell_to_child = -1;
+static int	shell_from_child = -1;
+static bool shell_sigchld_armed = false;
+static char shell_inbuf[MAXPGPATH];
+static int	shell_inlen = 0;
+static char shell_result_file[MAX_XFN_CHARS + 1];
+static char shell_outstanding[SHELL_OUTSTANDING_MAX][MAX_XFN_CHARS + 1];
+static int	shell_noutstanding = 0;
+static bool shell_report_retry = false;
+#endif
+
 const ArchiveModuleCallbacks *
 shell_archive_init(void)
 {
-	return &shell_archive_callbacks;
+#ifndef WIN32
+	if (XLogArchiveCommandPersistent)
+		return &shell_archive_async_callbacks;
+#endif
+	return &shell_archive_sync_callbacks;
 }
 
 static bool
 shell_archive_configured(ArchiveModuleState *state)
 {
-	if (XLogArchiveCommand[0] != '\0')
-		return true;
+	(void) state;
 
-	arch_module_check_errdetail("\"%s\" is not set.",
-								"archive_command");
-	return false;
+	if (XLogArchiveCommand[0] == '\0')
+	{
+		arch_module_check_errdetail("\"%s\" is not set.",
+									"archive_command");
+		return false;
+	}
+
+#ifndef WIN32
+	if (XLogArchiveCommandPersistent &&
+		shell_command_has_file_placeholders(XLogArchiveCommand))
+	{
+		arch_module_check_errdetail("\"archive_command\" must not contain %%f or %%p when \"archive_command_persistent\" is on.");
+		return false;
+	}
+#endif
+	return true;
 }
 
 static bool
@@ -136,8 +215,605 @@ shell_archive_file(ArchiveModuleState *state, const char *file,
 	return true;
 }
 
+#ifndef WIN32
+
+static bool
+shell_command_has_file_placeholders(const char *cmd)
+{
+	const char *p;
+
+	for (p = cmd; *p != '\0'; p++)
+	{
+		if (p[0] != '%')
+			continue;
+		if (p[1] == '%')
+		{
+			p++;
+			continue;
+		}
+		if (p[1] == 'f' || p[1] == 'p')
+			return true;
+		if (p[1] != '\0')
+			p++;
+	}
+	return false;
+}
+
+static void
+shell_sigchld_handler(SIGNAL_ARGS)
+{
+	int			save_errno = errno;
+
+	SetLatch(MyLatch);
+	errno = save_errno;
+}
+
+static void
+shell_prepare_child(void)
+{
+	int			sigs[] = {
+		SIGHUP, SIGINT, SIGTERM, SIGQUIT, SIGALRM,
+		SIGPIPE, SIGUSR1, SIGUSR2, SIGCHLD
+	};
+	int			i;
+
+	for (i = 0; i < lengthof(sigs); i++)
+		pqsignal(sigs[i], PG_SIG_DFL);
+	sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
+
+	/*
+	 * Become a process group leader so cancel/shutdown can signal the shell
+	 * and any grandchildren it forked.  On Debian, /bin/sh is dash and does
+	 * not exec a simple command, so kill(shell_pid) alone leaves the helper
+	 * alive.  Match postmaster's treatment of children that called setsid().
+	 */
+#ifdef HAVE_SETSID
+	if (setsid() < 0)
+		_exit(126);
+#endif
+}
+
+static void
+shell_reset_child(void)
+{
+	if (shell_to_child >= 0)
+	{
+		close(shell_to_child);
+		shell_to_child = -1;
+	}
+	if (shell_from_child >= 0)
+	{
+		close(shell_from_child);
+		shell_from_child = -1;
+	}
+	shell_child_pid = 0;
+	shell_inlen = 0;
+}
+
+/*
+ * Signal the persistent helper.  Like postmaster's signal_child(), send the
+ * signal both to the direct child and to its process group so grandchildren
+ * (e.g. dash forking instead of exec'ing the helper) are covered.
+ */
+static void
+shell_signal_child(int signal)
+{
+	if (kill(shell_child_pid, signal) < 0 && errno != ESRCH)
+		ereport(LOG,
+				(errmsg("could not signal archive command: %m")));
+#ifdef HAVE_SETSID
+	if (kill(-shell_child_pid, signal) < 0 && errno != ESRCH)
+		ereport(LOG,
+				(errmsg("could not signal archive command process group: %m")));
+#endif
+}
+
+static void
+shell_kill_child(void)
+{
+	int			status;
+	int			tries;
+
+	if (shell_child_pid > 0)
+	{
+		/* Close stdin first so helpers that read until EOF can exit. */
+		if (shell_to_child >= 0)
+		{
+			close(shell_to_child);
+			shell_to_child = -1;
+		}
+
+		shell_signal_child(SIGTERM);
+
+		for (tries = 0; tries < 10; tries++)
+		{
+			pid_t		done = waitpid(shell_child_pid, &status, WNOHANG);
+
+			if (done == shell_child_pid || (done < 0 && errno != EINTR))
+				break;
+			if (done < 0 && errno == EINTR)
+				continue;
+
+			pg_usleep(10000L);
+		}
+
+		if (waitpid(shell_child_pid, &status, WNOHANG) == 0)
+		{
+			shell_signal_child(SIGKILL);
+			while (waitpid(shell_child_pid, &status, WNOHANG) == 0)
+				pg_usleep(10000L);
+		}
+	}
+	shell_reset_child();
+}
+
+static bool
+shell_child_alive(void)
+{
+	int			status;
+	pid_t		done;
+
+	if (shell_child_pid <= 0)
+		return false;
+
+	for (;;)
+	{
+		done = waitpid(shell_child_pid, &status, WNOHANG);
+		if (!(done < 0 && errno == EINTR))
+			break;
+	}
+
+	if (done == 0)
+		return true;
+
+	if (done == shell_child_pid)
+	{
+		if (status != 0)
+			ereport(LOG,
+					(errmsg("persistent archive command failed: %s",
+							wait_result_to_str(status))));
+	}
+	else if (done < 0)
+		ereport(LOG,
+				(errmsg("could not wait for archive command: %m")));
+
+	shell_reset_child();
+	return false;
+}
+
+static bool
+shell_outstanding_add(const char *file)
+{
+	int			i;
+
+	if (shell_noutstanding >= XLogArchiveAsyncMax ||
+		shell_noutstanding >= SHELL_OUTSTANDING_MAX)
+		return false;
+
+	for (i = 0; i < shell_noutstanding; i++)
+	{
+		if (strcmp(shell_outstanding[i], file) == 0)
+			return false;
+	}
+
+	strlcpy(shell_outstanding[shell_noutstanding], file,
+			sizeof(shell_outstanding[0]));
+	shell_noutstanding++;
+	return true;
+}
+
+static bool
+shell_outstanding_remove(const char *file)
+{
+	int			i;
+
+	for (i = 0; i < shell_noutstanding; i++)
+	{
+		if (strcmp(shell_outstanding[i], file) == 0)
+		{
+			if (i < --shell_noutstanding)
+				strlcpy(shell_outstanding[i],
+						shell_outstanding[shell_noutstanding],
+						sizeof(shell_outstanding[0]));
+			return true;
+		}
+	}
+	return false;
+}
+
+static void
+shell_fail_outstanding(void)
+{
+	if (shell_noutstanding > 0)
+		shell_report_retry = true;
+	shell_kill_child();
+}
+
+static bool
+shell_take_retry(const char **file, ArchiveResultStatus *status)
+{
+	if (!shell_report_retry || shell_noutstanding <= 0)
+		return false;
+
+	shell_noutstanding--;
+	strlcpy(shell_result_file, shell_outstanding[shell_noutstanding],
+			sizeof(shell_result_file));
+	if (shell_noutstanding == 0)
+		shell_report_retry = false;
+	*file = shell_result_file;
+	*status = ARCHIVE_RESULT_RETRY;
+	return true;
+}
+
+/*
+ * Write one protocol line to the helper.
+ * Returns 1 on success, 0 on backpressure (EAGAIN), -1 on hard error.
+ */
+static int
+shell_write_line(const char *line)
+{
+	size_t		len = strlen(line);
+	size_t		off = 0;
+
+	while (off < len)
+	{
+		ssize_t		rc = write(shell_to_child, line + off, len - off);
+
+		if (rc < 0)
+		{
+			if (errno == EINTR)
+				continue;
+			/*
+			 * Backpressure is only safe before any bytes of this line were
+			 * queued.  A partial line would desynchronize the protocol.
+			 */
+			if ((errno == EAGAIN || errno == EWOULDBLOCK) && off == 0)
+				return 0;
+			ereport(LOG,
+					(errmsg("could not write to archive command: %m")));
+			return -1;
+		}
+		off += (size_t) rc;
+	}
+	return 1;
+}
+
+static bool
+shell_read_line(char *buf, size_t buflen, long timeout_ms)
+{
+	TimestampTz deadline = 0;
+	bool		have_deadline = false;
+
+	if (timeout_ms > 0)
+	{
+		deadline = GetCurrentTimestamp() + timeout_ms * 1000;
+		have_deadline = true;
+	}
+
+	if (!shell_sigchld_armed)
+	{
+		pqsignal(SIGCHLD, shell_sigchld_handler);
+		shell_sigchld_armed = true;
+	}
+
+	for (;;)
+	{
+		char	   *nl;
+		long		wait_ms;
+		int			rc;
+		ssize_t		nread;
+
+		nl = memchr(shell_inbuf, '\n', shell_inlen);
+		if (nl != NULL)
+		{
+			size_t		linelen = nl - shell_inbuf;
+
+			if (linelen >= buflen)
+			{
+				ereport(LOG,
+						(errmsg("archive command response line too long")));
+				shell_fail_outstanding();
+				return false;
+			}
+			memcpy(buf, shell_inbuf, linelen);
+			buf[linelen] = '\0';
+			if (linelen > 0 && buf[linelen - 1] == '\r')
+				buf[linelen - 1] = '\0';
+			linelen++;
+			shell_inlen -= linelen;
+			memmove(shell_inbuf, shell_inbuf + linelen, shell_inlen);
+			return true;
+		}
+
+		if (shell_report_retry)
+			return false;
+		if (!shell_child_alive())
+		{
+			shell_fail_outstanding();
+			return false;
+		}
+
+		if (have_deadline)
+		{
+			long		secs;
+			int			usecs;
+
+			if (TimestampDifferenceExceeds(deadline, GetCurrentTimestamp(), 0))
+				return false;
+			TimestampDifference(GetCurrentTimestamp(), deadline, &secs, &usecs);
+			wait_ms = secs * 1000 + usecs / 1000;
+			if (wait_ms <= 0)
+				wait_ms = 1;
+		}
+		else
+			wait_ms = 0;
+
+		rc = WaitLatchOrSocket(MyLatch,
+							  WL_LATCH_SET | WL_TIMEOUT |
+							  WL_SOCKET_READABLE | WL_EXIT_ON_PM_DEATH,
+							  shell_from_child,
+							  wait_ms,
+							  WAIT_EVENT_ARCHIVE_COMMAND);
+		ResetLatch(MyLatch);
+
+		if (!(rc & WL_SOCKET_READABLE))
+		{
+			if (!have_deadline)
+				return false;
+			continue;
+		}
+
+		if (shell_inlen >= (int) sizeof(shell_inbuf))
+		{
+			ereport(LOG,
+					(errmsg("archive command response line too long")));
+			shell_fail_outstanding();
+			return false;
+		}
+
+		nread = read(shell_from_child, shell_inbuf + shell_inlen,
+					 sizeof(shell_inbuf) - shell_inlen);
+		if (nread < 0)
+		{
+			if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)
+				continue;
+			ereport(LOG,
+					(errmsg("could not read from archive command: %m")));
+			shell_fail_outstanding();
+			return false;
+		}
+		if (nread == 0)
+		{
+			shell_fail_outstanding();
+			return false;
+		}
+		shell_inlen += (int) nread;
+
+		if (!have_deadline)
+		{
+			nl = memchr(shell_inbuf, '\n', shell_inlen);
+			if (nl == NULL)
+				return false;
+		}
+	}
+}
+
+static bool
+shell_parse_result(const char *line, char *file, size_t filelen,
+				   ArchiveResultStatus *status)
+{
+	const char *file_start;
+	const char *file_end;
+	const char *result;
+	size_t		n;
+
+	if (strncmp(line, "archived\t", 9) != 0)
+		return false;
+
+	file_start = line + 9;
+	file_end = strchr(file_start, '\t');
+	if (file_end == NULL || file_end == file_start)
+		return false;
+
+	n = file_end - file_start;
+	if (n >= filelen)
+		return false;
+	memcpy(file, file_start, n);
+	file[n] = '\0';
+
+	result = file_end + 1;
+	if (strcmp(result, "ok") == 0)
+		*status = ARCHIVE_RESULT_SUCCESS;
+	else if (strcmp(result, "retry") == 0)
+		*status = ARCHIVE_RESULT_RETRY;
+	else if (strcmp(result, "fail") == 0)
+		*status = ARCHIVE_RESULT_FAIL;
+	else
+		return false;
+	return true;
+}
+
+static bool
+shell_spawn_child(void)
+{
+	int			inpipe[2];
+	int			outpipe[2];
+	pid_t		pid;
+
+	if (pipe(inpipe) < 0)
+	{
+		ereport(LOG,
+				(errcode_for_socket_access(),
+				 errmsg("could not create pipe for archive command: %m")));
+		return false;
+	}
+	if (pipe(outpipe) < 0)
+	{
+		ereport(LOG,
+				(errcode_for_socket_access(),
+				 errmsg("could not create pipe for archive command: %m")));
+		close(inpipe[0]);
+		close(inpipe[1]);
+		return false;
+	}
+
+	fflush(NULL);
+	pid = fork_process();
+	if (pid == 0)
+	{
+		shell_prepare_child();
+		close(inpipe[1]);
+		close(outpipe[0]);
+		if (dup2(inpipe[0], STDIN_FILENO) < 0 ||
+			dup2(outpipe[1], STDOUT_FILENO) < 0)
+			_exit(126);
+		close(inpipe[0]);
+		close(outpipe[1]);
+		execl("/bin/sh", "sh", "-c", XLogArchiveCommand, (char *) NULL);
+		_exit(127);
+	}
+
+	close(inpipe[0]);
+	close(outpipe[1]);
+	if (pid < 0)
+	{
+		ereport(LOG,
+				(errmsg("could not fork archive command: %m")));
+		close(inpipe[1]);
+		close(outpipe[0]);
+		return false;
+	}
+
+	shell_child_pid = pid;
+	shell_to_child = inpipe[1];
+	shell_from_child = outpipe[0];
+	shell_inlen = 0;
+	if (!pg_set_noblock(shell_to_child) ||
+		!pg_set_noblock(shell_from_child))
+	{
+		ereport(LOG,
+				(errmsg("could not set nonblocking mode for archive command pipe: %m")));
+		shell_kill_child();
+		return false;
+	}
+
+	ereport(DEBUG1,
+			(errmsg_internal("started persistent archive command \"%s\"",
+							 XLogArchiveCommand)));
+	return true;
+}
+
+static bool
+shell_ensure_child(void)
+{
+	if (shell_child_pid > 0)
+	{
+		if (shell_child_alive())
+			return true;
+
+		shell_fail_outstanding();
+		if (shell_report_retry)
+			return false;
+	}
+	return shell_spawn_child();
+}
+
+static bool
+shell_archive_submit(ArchiveModuleState *state,
+					 const char *file,
+					 const char *path)
+{
+	char		line[MAXPGPATH + MAX_XFN_CHARS + 32];
+	char		nativePath[MAXPGPATH];
+
+	(void) state;
+
+	if (shell_report_retry)
+		return false;
+	if (shell_noutstanding >= XLogArchiveAsyncMax)
+		return false;
+	if (!shell_ensure_child())
+		return false;
+
+	strlcpy(nativePath, path, sizeof(nativePath));
+	make_native_path(nativePath);
+
+	if (!shell_outstanding_add(file))
+		return false;
+
+	snprintf(line, sizeof(line), "archive\t%s\t%s\n", file, nativePath);
+	switch (shell_write_line(line))
+	{
+		case 1:
+			return true;
+		case 0:
+			/* Pipe full: leave helper alone and ask caller to back off. */
+			shell_outstanding_remove(file);
+			return false;
+		default:
+			shell_outstanding_remove(file);
+			shell_fail_outstanding();
+			return false;
+	}
+}
+
+static bool
+shell_archive_poll(ArchiveModuleState *state, const char **file,
+				   ArchiveResultStatus *status, long timeout_ms)
+{
+	char		line[MAXPGPATH];
+
+	(void) state;
+
+	if (shell_take_retry(file, status))
+		return true;
+
+	if (shell_child_pid <= 0)
+	{
+		if (shell_noutstanding > 0)
+		{
+			shell_fail_outstanding();
+			return shell_take_retry(file, status);
+		}
+		return false;
+	}
+
+	if (!shell_read_line(line, sizeof(line), timeout_ms))
+		return shell_take_retry(file, status);
+
+	if (!shell_parse_result(line, shell_result_file, sizeof(shell_result_file),
+						   status) ||
+		!shell_outstanding_remove(shell_result_file))
+	{
+		ereport(LOG,
+				(errmsg("archive command sent bad response \"%s\"", line)));
+		shell_fail_outstanding();
+		return shell_take_retry(file, status);
+	}
+
+	*file = shell_result_file;
+	if (*status == ARCHIVE_RESULT_SUCCESS)
+		elog(DEBUG1, "archived write-ahead log file \"%s\"", shell_result_file);
+	return true;
+}
+
+static void
+shell_archive_cancel(ArchiveModuleState *state)
+{
+	(void) state;
+	shell_noutstanding = 0;
+	shell_report_retry = false;
+	shell_kill_child();
+}
+
+#endif										/* !WIN32 */
+
 static void
 shell_archive_shutdown(ArchiveModuleState *state)
 {
+	(void) state;
+#ifndef WIN32
+	shell_archive_cancel(state);
+#endif
 	elog(DEBUG1, "archiver process shutting down");
 }
diff --git a/src/backend/postmaster/pgarch.c b/src/backend/postmaster/pgarch.c
index e1122f7..b36aece 100644
--- a/src/backend/postmaster/pgarch.c
+++ b/src/backend/postmaster/pgarch.c
@@ -149,6 +149,8 @@ typedef struct ArchInFlight
 static ArchInFlight arch_inflight[ARCHIVE_ASYNC_SLOT_LIMIT];
 static int	arch_inflight_count = 0;
 static bool archiver_use_async = false;
+static bool archiver_shell_persistent = false;
+static char *archiver_shell_command = NULL;
 
 /*
  * Flags set by interrupt handlers for later service in the main loop.
@@ -1273,6 +1275,7 @@ ProcessPgArchInterrupts(void)
 	{
 		char	   *archiveLib = pstrdup(XLogArchiveLibrary);
 		bool		archiveLibChanged;
+		bool		old_persistent = XLogArchiveCommandPersistent;
 
 		ConfigReloadPending = false;
 		ProcessConfigFile(PGC_SIGHUP);
@@ -1304,6 +1307,30 @@ ProcessPgArchInterrupts(void)
 			proc_exit(0);
 		}
 
+		/*
+		 * Persistent vs classic shell archiving selects different module
+		 * callbacks at archiver start, so adopt the new mode via restart.
+		 * Likewise, a persistent helper is started with a fixed command
+		 * string, so restart when that command changes under persistent
+		 * mode.
+		 */
+		if (old_persistent != XLogArchiveCommandPersistent)
+		{
+			ereport(LOG,
+					(errmsg("restarting archiver process because value of "
+							"\"archive_command_persistent\" was changed")));
+			proc_exit(0);
+		}
+
+		if (archiver_shell_persistent &&
+			archiver_shell_command != NULL &&
+			strcmp(archiver_shell_command, XLogArchiveCommand) != 0)
+		{
+			ereport(LOG,
+					(errmsg("restarting archiver process because value of "
+							"\"archive_command\" was changed")));
+			proc_exit(0);
+		}
 	}
 }
 
@@ -1359,6 +1386,15 @@ LoadArchiveLibrary(void)
 		ereport(ERROR,
 				(errmsg("archive modules must register an archive callback")));
 
+	/*
+	 * Remember the shell settings used for this archiver lifetime so SIGHUP
+	 * can decide whether a restart is required.
+	 */
+	archiver_shell_persistent = XLogArchiveCommandPersistent;
+	if (archiver_shell_command)
+		pfree(archiver_shell_command);
+	archiver_shell_command = pstrdup(XLogArchiveCommand);
+
 	archive_module_state = palloc0_object(ArchiveModuleState);
 	if (ArchiveCallbacks->startup_cb != NULL)
 		ArchiveCallbacks->startup_cb(archive_module_state);
diff --git a/src/backend/utils/misc/guc_parameters.dat b/src/backend/utils/misc/guc_parameters.dat
index eeefbf0..ca61f1e 100644
--- a/src/backend/utils/misc/guc_parameters.dat
+++ b/src/backend/utils/misc/guc_parameters.dat
@@ -69,7 +69,7 @@
 
 { name => 'archive_async_max', type => 'int', context => 'PGC_SIGHUP', group => 'WAL_ARCHIVING',
   short_desc => 'Sets the maximum number of WAL files in flight for asynchronous archiving.',
-  long_desc => 'Used by asynchronous archive modules. Ignored by synchronous archive_file_cb modules.',
+  long_desc => 'Used by asynchronous archive modules and by persistent archive_command. Ignored by synchronous archive_file_cb modules.',
   variable => 'XLogArchiveAsyncMax',
   boot_val => '8',
   min => '1',
@@ -90,6 +90,14 @@
   show_hook => 'show_archive_command',
 },
 
+{ name => 'archive_command_persistent', type => 'bool', context => 'PGC_SIGHUP', group => 'WAL_ARCHIVING',
+  short_desc => 'Runs archive_command as a long-lived process fed over stdin.',
+  long_desc => 'When on, PostgreSQL starts archive_command once and feeds it ready WAL file names. The command must not contain %f or %p placeholders.',
+  variable => 'XLogArchiveCommandPersistent',
+  boot_val => 'false',
+  check_hook => 'check_archive_command_persistent',
+},
+
 { name => 'archive_library', type => 'string', context => 'PGC_SIGHUP', group => 'WAL_ARCHIVING',
   short_desc => 'Sets the library that will be called to archive a WAL file.',
   long_desc => 'An empty string means use "archive_command".',
diff --git a/src/backend/utils/misc/postgresql.conf.sample b/src/backend/utils/misc/postgresql.conf.sample
index f1d8033..df46bc2 100644
--- a/src/backend/utils/misc/postgresql.conf.sample
+++ b/src/backend/utils/misc/postgresql.conf.sample
@@ -299,6 +299,7 @@
                                 # be used)
 #archive_async_max = 8          # max in-flight files for async archiving
 #archive_command = ''           # command to use to archive a WAL file
+#archive_command_persistent = off # feed archive_command over stdin
                                 # placeholders: %p = path of file to archive
                                 #               %f = file name only
                                 # e.g. 'test ! -f "/mnt/server/archivedir/%f" && cp "%p" "/mnt/server/archivedir/%f"'
diff --git a/src/include/access/xlog.h b/src/include/access/xlog.h
index b57f747..18ee813 100644
--- a/src/include/access/xlog.h
+++ b/src/include/access/xlog.h
@@ -44,6 +44,7 @@ extern PGDLLIMPORT int XLOGbuffers;
 extern PGDLLIMPORT int XLogArchiveTimeout;
 extern PGDLLIMPORT int wal_retrieve_retry_interval;
 extern PGDLLIMPORT char *XLogArchiveCommand;
+extern PGDLLIMPORT bool XLogArchiveCommandPersistent;
 extern PGDLLIMPORT int XLogArchiveAsyncMax;
 extern PGDLLIMPORT bool EnableHotStandby;
 extern PGDLLIMPORT bool fullPageWrites;
diff --git a/src/include/utils/guc_hooks.h b/src/include/utils/guc_hooks.h
index 8e3c067..b20315e 100644
--- a/src/include/utils/guc_hooks.h
+++ b/src/include/utils/guc_hooks.h
@@ -29,6 +29,8 @@ extern bool check_application_name(char **newval, void **extra,
 								   GucSource source);
 extern void assign_application_name(const char *newval, void *extra);
 extern const char *show_archive_command(void);
+extern bool check_archive_command_persistent(bool *newval, void **extra,
+											 GucSource source);
 extern bool check_autovacuum_work_mem(int *newval, void **extra,
 									  GucSource source);
 extern bool check_vacuum_buffer_usage_limit(int *newval, void **extra,
-- 
2.56.1

