NetBSD-Bugs archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]
bin/48183: Example in man write(2) causes endless loop
>Number: 48183
>Category: bin
>Synopsis: Example in man write(2) causes endless loop
>Confidential: no
>Severity: non-critical
>Priority: low
>Responsible: bin-bug-people
>State: open
>Class: doc-bug
>Submitter-Id: net
>Arrival-Date: Wed Sep 04 23:30:00 +0000 2013
>Originator: Manuel Wiesinger
>Release: 6.99.23
>Organization:
>Environment:
NetBSD scampi 6.99.23 NetBSD 6.99.23 (GENERIC) #0: Fri Jul 19 21:47:43 CEST
2013 manuel@scampi:/usr/obj/sys/arch/amd64/compile/GENERIC amd64
>Description:
The manpage of pread says:
Proper loops should use
while ((nr = write(fd, buf, sizeof(buf))) != -1 && nr != 0)
which is clearly an endless loop. Say nr = 512 and the write is successful,
then 512 != -1 && n1 !=0 is true.
>How-To-Repeat:
Compile this C program:
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int
main()
{
off_t blk, new_blk;
ssize_t w;
char buf[] = "heydo";
int fd = open("/tmp/test", O_WRONLY | O_CREAT);
while ((w = write(fd, buf, sizeof(buf))) != -1 && w != 0)
printf("w: %ld\n", w);
return 1;
}
>Fix:
Suggest something like the following.
When zero bytes have been written, or the write has failed error handling is
necessary.
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int
main()
{
off_t blk, new_blk;
ssize_t w;
char buf[] = "heydo";
int fd = open("/tmp/test", O_WRONLY | O_CREAT);
while ((w = write(fd, buf, sizeof(buf))) != sizeof(buf)) {
if(w == 0 || w == -1)
errx(EXIT_FAILURE, "could not write\n");
}
return 1;
}
Home |
Main Index |
Thread Index |
Old Index