Hi,

Todd C. Miller wrote on Mon, Sep 18, 2017 at 09:35:45AM -0600:
> On Mon, 18 Sep 2017 16:50:41 +0200, Ingo Schwarze wrote:

>> Indeed, the above code is nonsensical.
>> It will write the same bytes repeatedly in case of partial writes.

> OK millert@

Committed, thanks for checking.

> That does look much better, though I'm not convinced that write(2)
> will ever return 0 unless nbytes is also 0.  POSIX doesn't
> disallow this so I suppose we must assume it could happen.

I admit to a small amount of cargo cult:  Our very own cat(1)
implementation checks against 0, for example.

In addition to your argument that POSIX does not clearly prohibit
implementations from containing exotic devices performing 0-byte
partial writes, the RATIONALE in POSIX also says this:

  Where this volume of POSIX.1-2008 requires -1 to be returned and
  errno set to [EAGAIN], most historical implementations return
  zero (with the O_NDELAY flag set, which is the historical predecessor
  of O_NONBLOCK, but is not itself in this volume of POSIX.1-2008).
  The error indications in this volume of POSIX.1-2008 were chosen
  so that an application can distinguish these cases from end-of-file.
  While write() cannot receive an indication of end-of-file, read()
  can, and the two functions have similar return values. Also, some
  existing systems (for example, Eighth Edition) permit a write of
  zero bytes to mean that the reader should get an end-of-file
  indication; for those systems, a return value of zero from write()
  indicates a successful write of an end-of-file indication.

So, apart from being safer for weird devices on weird implementations,
POSIX clearly recommends the idiom for symmetry with read(2) and
for compatibility with some historic implementations - even though
the importance of these reasons is likely to further decline, there
are so many different reasons that retaining the idiom seems the
safest bet.

> However, if it did, in your example err() will use some an old errno
> value.  I don't think this is actually possible so it is not worth
> cluttering up the error reporting in the example.

Right.  Those arcane dangers are not a good reason for turning a
simple and frequently used three-line idiom into an unwieldy
seven-line monster.

Besides, i consider "cat: stdout: Undefined error: 0" to be a
totally appropriate error message, which clearly indicates that
something went really awry in a very unusual way.  Even if you
would ask me to add four more lines to cat.c to handle a 0 return
value with a different error message, i would be totally at a loss
what better to say.

And if another error happened before, chances are it might even be
related, so overriding the errno might sometimes even hide
information...

And finally, even a suboptimal error message would be much better
than embarking on an infinite loop.

Yours,
  Ingo

Reply via email to