Re: Sometimes the output to the stdout in Windows disappears - Mailing list pgsql-hackers

From Tom Lane
Subject Re: Sometimes the output to the stdout in Windows disappears
Date
Msg-id 4156857.1602865112@sss.pgh.pa.us
Whole thread Raw
In response to Re: Sometimes the output to the stdout in Windows disappears  (Alexander Lakhin <exclusion@gmail.com>)
Responses Re: Sometimes the output to the stdout in Windows disappears
Re: Sometimes the output to the stdout in Windows disappears
List pgsql-hackers
Alexander Lakhin <exclusion@gmail.com> writes:
> I've managed to make a simple reproducer. Please look at the patch attached.
> There are two things crucial for reproducing the bug:
>     ioctlsocket(sock, FIONBIO, &ioctlsocket_ret); // from pgwin32_socket()
> and
>     WSACleanup();

Oh, very interesting.

Now that you have it somewhat in captivity, maybe you could determine
some things:

1. Is it only stdout that's affected?  What of other stdio streams?
(Note that testing stderr might be tricky because it's probably
line-buffered.)

2. Does an fflush() just before, or just after, WSACleanup() fix it?

> I see no solution for this on the postgres side for now, but this
> information about Windows quirks could be useful in case someone
> stumbled upon it too.

Depending on your answers to the above, maybe some hack like this
would be acceptable:

     free(conn);

 #ifdef WIN32
+    fflush(NULL);
     WSACleanup();
 #endif
 }

It's not very nice for a library to be doing global things like that,
but if the alternative is loss of output, maybe we should.

But wait a minute: I just looked at Microsoft's docs [1] and found

    In a multithreaded environment, WSACleanup terminates Windows Sockets
    operations for all threads.

This makes me (a) wonder if that explains the side-effects on stdio,
and (b) question why libpq is calling WSACleanup at all.
What if we arranged to call WSAStartup just once, during the first
libpq connection-open in a process, and then never did WSACleanup?
Surely the OS can cope with that, and it eliminates any risk that
WSACleanup breaks something.

            regards, tom lane

[1] https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsacleanup



pgsql-hackers by date:

Previous
From: Alvaro Herrera
Date:
Subject: Re: Feature improvement: can we add queryId for pg_catalog.pg_stat_activity view?
Next
From: Tom Lane
Date:
Subject: Re: Feature improvement: can we add queryId for pg_catalog.pg_stat_activity view?