In initdb, ensure stdout/stderr buffering behavior is what we expect.
authorTom Lane <tgl@sss.pgh.pa.us>
Thu, 15 May 2014 01:13:54 +0000 (21:13 -0400)
committerTom Lane <tgl@sss.pgh.pa.us>
Thu, 15 May 2014 01:14:25 +0000 (21:14 -0400)
Since this program may print to either stdout or stderr, the relative
ordering of its messages depends on the buffering behavior of those files.
Force stdout to be line-buffered and stderr to be unbuffered, ensuring
that the behavior will match standard Unix interactive behavior, even
when stdout and stderr are rerouted to a file.

Per complaint from Tomas Vondra.  The particular case he pointed out is
new in HEAD, but issues of the same sort could arise in any branch with
other error messages, so back-patch to all branches.

I'm unsure whether we might not want to do this in other client programs
as well.  For the moment, just fix initdb.

src/bin/initdb/initdb.c

index ec3b5e1876ceb4db88ac81e3d2c0bf4257697570..acaae029806b9a4f10e3845afee7772f8d86ab40 100644 (file)
@@ -3523,6 +3523,15 @@ main(int argc, char *argv[])
    char       *effective_user;
    char        bin_dir[MAXPGPATH];
 
+   /*
+    * Ensure that buffering behavior of stdout and stderr matches what it is
+    * in interactive usage (at least on most platforms).  This prevents
+    * unexpected output ordering when, eg, output is redirected to a file.
+    * POSIX says we must do this before any other usage of these files.
+    */
+   setvbuf(stdout, NULL, _IOLBF, 0);
+   setvbuf(stderr, NULL, _IONBF, 0);
+
    progname = get_progname(argv[0]);
    set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("initdb"));