Greetings,

When the postmaster exits unexpectedly on Windows (crash, kill, debugger
abort), backend processes continue running. Windows lacks any equivalent
to Unix's getppid() orphan detection. These orphaned backends hold locks
and shared memory, preventing clean restart. This leads to a delay in
restarts and manual killing of orphans.

The problem is easy to reproduce. Start postgres, open a transaction
with LOCK TABLE, then kill the postmaster with taskkill /F. The backend
continues running and restart fails. Manual cleanup is required.

Current approaches (inherited event handles, shared memory flags) depend
on the postmaster running code during exit. A segfault or kill bypasses
all of that.

My proposed solution is to use Windows Job Objects with KILL_ON_JOB_CLOSE.

We just need to call CreateJobObject() in PostmasterMain(), configure
with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, and assign the postmaster.
Children inherit membership automatically. When the job handle closes on
postmaster exit, the kernel terminates all children atomically. This is
kernel-enforced with no polling and no race conditions.

Job creation can fail if postgres runs under an existing job (service
managers, debuggers). Windows 7 disallows nested jobs. We detect this
with IsProcessInJob(), and if AssignProcessToJobObject() returns
ERROR_ACCESS_DENIED, we log and continue without orphan protection.

KILL_ON_JOB_CLOSE doesn't interfere with clean shutdown. Normal shutdown
signals backends via SetEvent, they exit, postmaster exits, job closes.
Nothing left to kill. The flag only fires during crashes when backends
are still running - exactly when forced termination is correct.

The code is ~200 lines in pg_job_object.c, less than win32/signal.c
(~500 lines). It fails gracefully and works regardless of how postgres
is started, unlike service manager approaches. This avoids polling
unreliability.

The patch has been tested on Windows 10/11 with both MSVC and MinGW
builds. Nested jobs fail gracefully as expected. Clean shutdown is
unaffected. Crash tests with taskkill /F, debugger abort, and access
violations all correctly terminate children immediately with zero orphans.

This patch does not include automated tests because the core
functionality (orphan prevention on crash) requires simulating process
termination, which is difficult to test reliably in CI.

Patch attached. Can add documentation if this approach is approved.

Thoughts?

Bryan Green
From 4aea4fd2761e33244cbd55c21a9fbe64897fa732 Mon Sep 17 00:00:00 2001
From: Bryan Green <[email protected]>
Date: Thu, 30 Oct 2025 11:14:55 -0600
Subject: [PATCH] Use Windows Job Objects to prevent orphaned child processes.

When the postmaster exits on Windows, backends can continue running
because Windows lacks Unix's getppid() orphan detection. Orphaned
backends hold locks and shared memory, preventing clean restart.

Create a Job Object at postmaster startup and assign the postmaster
to it. Children inherit job membership automatically. Configure with
KILL_ON_JOB_CLOSE so the kernel terminates all children when the job
handle closes on postmaster exit.

This is more reliable than existing approaches (inherited handles,
shared memory flags) because it's kernel-enforced with no polling.

Job creation is allowed to fail non-fatally. Some environments run
PostgreSQL under an existing job, and Windows 7 disallows nested jobs.
In such cases we log a message and proceed without orphan protection.

Author: Bryan Green
---
 doc/src/sgml/runtime.sgml               |  21 +++
 src/backend/postmaster/postmaster.c     |  12 ++
 src/backend/storage/ipc/Makefile        |   4 +
 src/backend/storage/ipc/meson.build     |   7 +
 src/backend/storage/ipc/pg_job_object.c | 176 ++++++++++++++++++++++++
 src/include/storage/pg_job_object.h     |  35 +++++
 6 files changed, 255 insertions(+)
 create mode 100644 src/backend/storage/ipc/pg_job_object.c
 create mode 100644 src/include/storage/pg_job_object.h

diff --git a/doc/src/sgml/runtime.sgml b/doc/src/sgml/runtime.sgml
index 0c60bafac6..95784e9236 100644
--- a/doc/src/sgml/runtime.sgml
+++ b/doc/src/sgml/runtime.sgml
@@ -1501,6 +1501,27 @@ $ <userinput>cat 
/sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages</userinp
    </para>
 
   </sect2>
+
+  <sect2 id="windows-process-management">
+   <title>Process Management on <systemitem 
class="osname">Windows</systemitem></title>
+
+   <para>
+    On <systemitem class="osname">Windows</systemitem>,
+    <productname>PostgreSQL</productname> uses Job Objects to
+    manage child processes. If the postmaster exits unexpectedly
+    (due to a crash or external termination), the operating system
+    automatically terminates all backend processes. This prevents
+    orphaned backends that could hold locks or corrupt shared memory.
+   </para>
+
+   <para>
+    In some cases, Job Object creation may fail (for example, when
+    <productname>PostgreSQL</productname> is already running under a
+    job-aware service manager). The server will log a message and continue
+    to run without orphan protection. This is safe but means that backends
+    may need to be manually terminated if the postmaster crashes.
+   </para>
+  </sect2>
  </sect1>
 
 
diff --git a/src/backend/postmaster/postmaster.c 
b/src/backend/postmaster/postmaster.c
index 00de559ba8..14697b95e2 100644
--- a/src/backend/postmaster/postmaster.c
+++ b/src/backend/postmaster/postmaster.c
@@ -113,6 +113,7 @@
 #include "storage/fd.h"
 #include "storage/io_worker.h"
 #include "storage/ipc.h"
+#include "storage/pg_job_object.h"
 #include "storage/pmsignal.h"
 #include "storage/proc.h"
 #include "tcop/backend_startup.h"
@@ -1005,6 +1006,17 @@ PostmasterMain(int argc, char *argv[])
         */
        CreateSharedMemoryAndSemaphores();
 
+#ifdef WIN32
+       /*
+       * On Windows, create a job object to prevent orphaned backends.
+       * If postmaster crashes, Windows will automatically kill all
+       * child processes in the job.
+       *
+       * We do this after port binding so that if job creation fails,
+       * it's not fatal - we can still run (just without orphan protection).
+       */
+       pg_create_job_object();
+#endif
        /*
         * Estimate number of openable files.  This must happen after setting up
         * semaphores, because on some platforms semaphores count as open files.
diff --git a/src/backend/storage/ipc/Makefile b/src/backend/storage/ipc/Makefile
index 9a07f6e1d9..0604f4f382 100644
--- a/src/backend/storage/ipc/Makefile
+++ b/src/backend/storage/ipc/Makefile
@@ -28,4 +28,8 @@ OBJS = \
        standby.o \
        waiteventset.o
 
+ifeq ($(PORTNAME), win32)
+OBJS += pg_job_object.o
+endif
+
 include $(top_srcdir)/src/backend/common.mk
diff --git a/src/backend/storage/ipc/meson.build 
b/src/backend/storage/ipc/meson.build
index b1b73dac3b..85ba13b70d 100644
--- a/src/backend/storage/ipc/meson.build
+++ b/src/backend/storage/ipc/meson.build
@@ -21,3 +21,10 @@ backend_sources += files(
   'waiteventset.c',
 
 )
+
+# Windows-specific files
+if host_system == 'windows'
+  backend_sources += files(
+    'pg_job_object.c',
+  )
+endif
diff --git a/src/backend/storage/ipc/pg_job_object.c 
b/src/backend/storage/ipc/pg_job_object.c
new file mode 100644
index 0000000000..c84aeed9cd
--- /dev/null
+++ b/src/backend/storage/ipc/pg_job_object.c
@@ -0,0 +1,176 @@
+/*-------------------------------------------------------------------------
+ *
+ * pg_job_object.c
+ *       Windows Job Object support for preventing orphaned backends
+ *
+ * On Unix, backends can detect when the postmaster dies via getppid().
+ * Windows has no equivalent mechanism. We solve this by using Job Objects,
+ * a Windows kernel feature that groups processes and can automatically
+ * terminate all members when the job handle closes.
+ *
+ * By configuring JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, we ensure that if
+ * the postmaster exits (cleanly or via crash), Windows immediately kills
+ * all backends. This prevents orphaned processes that hold locks and
+ * prevent clean restart.
+ *
+ * The job object handle is stored in a static variable and never explicitly
+ * closed. This is intentional - we rely on Windows closing it automatically
+ * when the postmaster process exits, which triggers the child termination.
+ *
+ * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ *       src/backend/storage/ipc/pg_job_object.c
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#include "postgres.h"
+
+#ifdef WIN32
+
+#include "postmaster/postmaster.h"
+#include "storage/ipc.h"
+#include "storage/pg_job_object.h"
+
+static HANDLE pg_job_object = NULL;
+
+
+/*
+ * pg_create_job_object
+ *
+ * Create job object for this PostgreSQL instance and configure it to
+ * kill all children when the postmaster exits.
+ *
+ * Failure is not fatal - we log a warning and continue. PostgreSQL will
+ * run without orphan protection, which is no worse than current behavior.
+ */
+void
+pg_create_job_object(void)
+{
+       JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit_info;
+       char            job_name[128];
+       DWORD           error;
+
+       snprintf(job_name, sizeof(job_name), "PostgreSQL_Port_%d_PID_%lu",
+                        PostPortNumber, GetCurrentProcessId());
+
+       pg_job_object = CreateJobObjectA(NULL, job_name);
+
+       if (pg_job_object == NULL)
+       {
+               error = GetLastError();
+               ereport(LOG,
+                               (errmsg("could not create job object \"%s\": 
error code %lu",
+                                               job_name, error),
+                                errdetail("Orphaned process cleanup will not 
be available.")));
+               return;
+       }
+
+       elog(DEBUG1, "created job object \"%s\"", job_name);
+
+       /*
+        * Set KILL_ON_JOB_CLOSE. When the job handle closes (either explicit
+        * close or process termination), all processes in the job are 
terminated.
+        *
+        * This is the critical flag that prevents orphaned backends.
+        */
+       memset(&limit_info, 0, sizeof(limit_info));
+       limit_info.BasicLimitInformation.LimitFlags = 
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
+
+       if (!SetInformationJobObject(pg_job_object,
+                                                                 
JobObjectExtendedLimitInformation,
+                                                                 &limit_info,
+                                                                 
sizeof(limit_info)))
+       {
+               error = GetLastError();
+               ereport(WARNING,
+                               (errmsg("could not configure job object: error 
code %lu", error),
+                                errdetail("Job object created but 
KILL_ON_JOB_CLOSE not set."),
+                                errhint("Orphaned processes may occur if 
postmaster crashes.")));
+               CloseHandle(pg_job_object);
+               pg_job_object = NULL;
+               return;
+       }
+
+       if (!AssignProcessToJobObject(pg_job_object, GetCurrentProcess()))
+       {
+               error = GetLastError();
+
+               /*
+                * ERROR_ACCESS_DENIED means we're already in a job. This can 
happen
+                * when PostgreSQL runs under a job-aware supervisor (Windows 
service
+                * on older Windows, or any process manager using nested jobs).
+                *
+                * On Windows 8+, we could use nested jobs, but for simplicity 
we
+                * just skip job creation. The parent job should handle cleanup.
+                */
+               if (error == ERROR_ACCESS_DENIED)
+               {
+                       ereport(LOG,
+                                       (errmsg("postmaster is already in a job 
object"),
+                                        errdetail("This can occur when 
PostgreSQL is run under a job-aware supervisor."),
+                                        errhint("Automatic orphan cleanup will 
not be available.")));
+               }
+               else
+               {
+                       ereport(WARNING,
+                                       (errmsg("could not assign postmaster to 
job object: error code %lu", error)));
+               }
+
+               CloseHandle(pg_job_object);
+               pg_job_object = NULL;
+               return;
+       }
+
+       elog(LOG, "PostgreSQL job object configured successfully - orphaned 
process prevention enabled");
+}
+
+
+/*
+ * pg_destroy_job_object
+ *
+ * Explicitly close the job object handle. This will trigger KILL_ON_JOB_CLOSE,
+ * terminating all backends.
+ *
+ * Note: In most cases we don't call this - we rely on Windows closing the
+ * handle automatically when the postmaster exits. Explicit close is only
+ * needed if we want to control the exact timing of backend termination.
+ */
+void
+pg_destroy_job_object(void)
+{
+       if (pg_job_object != NULL)
+       {
+               elog(DEBUG1, "closing job object - all child processes will 
terminate");
+               CloseHandle(pg_job_object);
+               pg_job_object = NULL;
+       }
+}
+
+
+/*
+ * pg_is_in_job_object
+ *
+ * Check if current process is in the PostgreSQL job object.
+ * Used primarily for testing and verification.
+ */
+bool
+pg_is_in_job_object(void)
+{
+       BOOL            in_job = FALSE;
+
+       if (pg_job_object == NULL)
+               return false;
+
+       if (!IsProcessInJob(GetCurrentProcess(), pg_job_object, &in_job))
+       {
+               elog(DEBUG1, "IsProcessInJob failed: error code %lu", 
GetLastError());
+               return false;
+       }
+
+       return (bool) in_job;
+}
+
+#endif                                                 /* WIN32 */
diff --git a/src/include/storage/pg_job_object.h 
b/src/include/storage/pg_job_object.h
new file mode 100644
index 0000000000..67de54be5b
--- /dev/null
+++ b/src/include/storage/pg_job_object.h
@@ -0,0 +1,35 @@
+/*-------------------------------------------------------------------------
+ *
+ * pg_job_object.h
+ *       Windows Job Object support for preventing orphaned backends
+ *
+ * When the postmaster crashes on Windows, child processes continue running
+ * because Windows has no equivalent to Unix's parent death detection. Job
+ * Objects solve this by allowing the kernel to terminate all children when
+ * the job handle closes (which happens automatically on process exit).
+ *
+ * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/storage/pg_job_object.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef PG_JOB_OBJECT_H
+#define PG_JOB_OBJECT_H
+
+#ifdef WIN32
+
+extern void pg_create_job_object(void);
+extern void pg_destroy_job_object(void);
+extern bool pg_is_in_job_object(void);
+
+#else                                                  /* !WIN32 */
+
+#define pg_create_job_object() ((void) 0)
+#define pg_destroy_job_object() ((void) 0)
+#define pg_is_in_job_object() (false)
+
+#endif                                                 /* WIN32 */
+
+#endif                                                 /* PG_JOB_OBJECT_H */
-- 
2.46.0.windows.1

Reply via email to