Be more correct in read_from_stdin()

From read(2) manual page on OpenBSD:

     Error checks should explicitly test for -1.  Code such as

           while ((nr = read(fd, buf, sizeof(buf))) > 0)

     is not maximally portable, as some platforms allow for nbytes to range
     between SSIZE_MAX and SIZE_MAX - 2, in which case the return value of an
     error-free read() may appear as a negative number distinct from -1.
     Proper loops should use

           while ((nr = read(fd, buf, sizeof(buf))) != -1 && nr != 0)

Distingushing between error and eof would also help for debugging.
This commit is contained in:
Dmitrij D. Czarkoff 2016-10-09 03:14:37 +02:00
parent e4ded04c39
commit f33b1a4a96

View file

@ -31,7 +31,10 @@ size_t read_from_stdin(void **buffer) {
for(*buffer = NULL; (*buffer = realloc((p = *buffer), len + step)); for(*buffer = NULL; (*buffer = realloc((p = *buffer), len + step));
len += (size_t)r) { len += (size_t)r) {
if((r = read(STDIN_FILENO, (uint8_t *)*buffer + len, step)) <= 0) { if((r = read(STDIN_FILENO, (uint8_t *)*buffer + len, step)) == -1) {
perror(NULL);
break;
} else if (r == 0) {
break; break;
} }
} }