bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Built-in printf Sits Awkwardly with UDP.


From: Ralph Corderoy
Subject: Re: Built-in printf Sits Awkwardly with UDP.
Date: Wed, 20 Jul 2011 14:34:24 +0100

Hi Bob,

> Ralph Corderoy wrote:
> > ...  But a regular file ./foo on disk does look different and it
> > still seems odd that
> >     printf '\n\n\n\n\n\n\n\n\n\n\n\n' >foo
> > does a dozen one-byte write(2)s.
> 
> But the only reason you know that there is a long string of newlines
> is that your eye is looking over the entire string.  It has all of the
> data all at once.  You have a non-causal relationship with the data
> because you are looking over all of the past history of the data.  By
> the time we see it here it has all already happened.  You are not
> looking at the data as it arrives.

This is true, but has no bearing on the issue.  :-)

> In other words...  Are you trying to suggest that a program should try
> to look-ahead at future characters?

No.  Here's my understanding of how it currently works.  The built-in
printf works out a character to print at a time;  no foresight needed or
used.  It asks the C library to print it with putchar(3).  The C library
can implement buffering to avoid too many expensive write(2) system
calls.  bash has the C library buffer stdout by lines.  Each time
putchar(3) is called the character is appended to the buffer.  If the
character was '\n' or the buffer is now full then write(2) is called to
pass the buffer to the kernel and the buffer then treated as empty.

When printf is finished the buffer is flushed, e.g. if there's anything
in it then write(2) is called.

The C library provides two other modes of buffering, see setvbuf(3).
bash could easily detect that stdout is a regular file, have a new
stream be duplicated from file descriptor 1, and set it to
block-buffered.  (POSIX doesn't permit a stream's buffering to change
once the stream has been written to;  but that's a downside of using the
C library's I/O model.)  That would lessen the number of write(2)s and
allow a single UDP packet to be sent with print containing a '\n'.

No change will be made, I see that.  Just didn't want to leave the false
suggestion that premonition is in any way involved.  :-)

BTW, the code for the built-in printf has a bug.  For negative
field-widths it negates a negative integer without checking it will fit.
E.g. on this 64-bit machine

    $ printf '%-9223372036854775808s.\n' foo
    foo.
    $

Cheers, Ralph.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]