Subject: bug#13498: "cut -f" lags a line

From: Eric Blake <[email-masked]>
Date: Thu, 29 May 2014 19:31:31 -0600

On 01/19/2013 01:04 PM, Andreas Schwab wrote:

[revisiting an old bug, since I just noticed it]

> Scott Lamb <[email-masked]> writes:
> 
>> I don't know exactly why the behavior differs based on stdin being a
>> tty or not. My best guess is that glibc might have some logic that, if
>> stdin is a tty, automatically flushes stdout any time the program
>> blocks on stdin.
> 
> When a new buffer is read for a line buffered or unbuffered stream,
> stdout is flushed.  This is traditional Unix behaviour, but AFAIK not
> required by any standard.

Actually, POSIX requires it:

http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_05

> When a stream is "unbuffered", bytes are intended to appear from the
> source or at the destination as soon as possible; otherwise, bytes may
> be accumulated and transmitted as a block. When a stream is "fully
> buffered", bytes are intended to be transmitted as a block when a buffer
> is filled. When a stream is "line buffered", bytes are intended to be
> transmitted as a block when a <newline> byte is encountered.
> Furthermore, bytes are intended to be transmitted as a block when a
> buffer is filled, when input is requested on an unbuffered stream, or
> when input is requested on a line-buffered stream that requires the
> transmission of bytes.

stdout is required to be buffered, and when stdin is the same terminal
as stdout, then stdin is line-buffered and it is sufficient that an
input line on stdin forces stdout to be flushed.

-- 
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org