Hi Marc, Marc Espie wrote on Sun, Sep 17, 2017 at 11:53:39AM +0200: > On Sat, Sep 16, 2017 at 10:25:19PM -0500, Scott Cheloha wrote:
>> The second example in the write(2) CAVEATS section is identical to >> the corresponding example in the read(2) page: >> >> while ((nr = write(fd, buf, sizeof(buf))) != -1 && nr != 0) > I'm for either scraping the example altogether Indeed, the above code is nonsensical. It will write the same bytes repeatedly in case of partial writes. > or writing a proper one, which would mean embedding any version > of safe_write in the man page. Here you are. Ingo Index: write.2 =================================================================== RCS file: /cvs/src/lib/libc/sys/write.2,v retrieving revision 1.39 diff -u -p -r1.39 write.2 --- write.2 5 Feb 2015 02:33:09 -0000 1.39 +++ write.2 18 Sep 2017 14:43:41 -0000 @@ -155,6 +155,18 @@ is returned. Otherwise, a \-1 is returned and the global variable .Va errno is set to indicate the error. +.Sh EXAMPLES +The typical loop allowing partial writes looks like this: +.Bd -literal +const char *buf; +size_t bsz, off; +ssize_t nw; +int d; + +for (off = 0; off < bsz; off += nw) + if ((nw = write(d, buf + off, bsz - off)) == 0 || nw == -1) + err(1, "write"); +.Ed .Sh ERRORS .Fn write , .Fn pwrite , @@ -309,21 +321,11 @@ function call appeared in .At v2 . .Sh CAVEATS Error checks should explicitly test for \-1. -Code such as -.Bd -literal -offset indent -while ((nr = write(fd, buf, sizeof(buf))) > 0) -.Ed -.Pp -is not maximally portable, as some platforms allow for +On some platforms, if .Fa nbytes -to range between +is larger than .Dv SSIZE_MAX -and +but smaller than .Dv SIZE_MAX -\- 2, in which case the return value of an error-free -.Fn write +\- 2, the return value of an error-free call may appear as a negative number distinct from \-1. -Proper loops should use -.Bd -literal -offset indent -while ((nr = write(fd, buf, sizeof(buf))) != -1 && nr != 0) -.Ed
