Skip to content

Commit 6251f86

Browse files
committed
On Windows, close the client socket explicitly during backend shutdown.
It turns out that this is necessary to keep Winsock from dropping any not-yet-sent data, such as an error message explaining the reason for process termination. It's pretty weird that the implicit close done by the kernel acts differently from an explicit close, but it's hard to argue with experimental results. Independently submitted by Alexander Lakhin and Lars Kanis (comments by me, though). Back-patch to all supported branches. Discussion: https://postgr.es/m/90b34057-4176-7bb0-0dbb-9822a5f6425b@greiz-reinsdorf.de Discussion: https://postgr.es/m/16678-253e48d34dc0c376@postgresql.org
1 parent fae5f08 commit 6251f86

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

src/backend/libpq/pqcomm.c

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -284,15 +284,28 @@ socket_close(int code, Datum arg)
284284
secure_close(MyProcPort);
285285

286286
/*
287-
* Formerly we did an explicit close() here, but it seems better to
288-
* leave the socket open until the process dies. This allows clients
289-
* to perform a "synchronous close" if they care --- wait till the
290-
* transport layer reports connection closure, and you can be sure the
291-
* backend has exited.
287+
* On most platforms, we leave the socket open until the process dies.
288+
* This allows clients to perform a "synchronous close" if they care
289+
* --- wait till the transport layer reports connection closure, and
290+
* you can be sure the backend has exited. Saves a kernel call, too.
292291
*
293-
* We do set sock to PGINVALID_SOCKET to prevent any further I/O,
294-
* though.
292+
* However, that does not work on Windows: if the kernel closes the
293+
* socket it will invoke an "abortive shutdown" that discards any data
294+
* not yet sent to the client. (This is a flat-out violation of the
295+
* TCP RFCs, but count on Microsoft not to care about that.) To get
296+
* the spec-compliant "graceful shutdown" behavior, we must invoke
297+
* closesocket() explicitly.
298+
*
299+
* This code runs late enough during process shutdown that we should
300+
* have finished all externally-visible shutdown activities, so that
301+
* in principle it's good enough to act as a synchronous close on
302+
* Windows too. But it's a lot more fragile than the other way.
295303
*/
304+
#ifdef WIN32
305+
closesocket(MyProcPort->sock);
306+
#endif
307+
308+
/* In any case, set sock to PGINVALID_SOCKET to prevent further I/O */
296309
MyProcPort->sock = PGINVALID_SOCKET;
297310
}
298311
}

0 commit comments

Comments
 (0)