diff --git a/src/fsendfile.c b/src/fsendfile.c index 88239ed..e32f3bc 100644 --- a/src/fsendfile.c +++ b/src/fsendfile.c @@ -53,6 +53,7 @@ ssize_t fsendfile(FILE *src, FILE *dst, size_t len) char *buf; size_t tot = 0; ssize_t blk = BUFSIZ, num = 0; + int saved_errno; if (!src) { errno = EINVAL; @@ -68,8 +69,11 @@ ssize_t fsendfile(FILE *src, FILE *dst, size_t len) blk = len - tot; num = fread(buf, 1, blk, src); - if (num == 0) + if (num == 0) { + if (ferror(src)) + num = -1; break; + } if (dst && (fwrite(buf, num, 1, dst) != 1)) { num = -1; @@ -79,7 +83,9 @@ ssize_t fsendfile(FILE *src, FILE *dst, size_t len) tot += num; } + saved_errno = errno; free(buf); + errno = saved_errno; return (num == -1) ? -1 : (ssize_t)tot; } diff --git a/test/fsendfile.c b/test/fsendfile.c index f0f22f3..51951ee 100644 --- a/test/fsendfile.c +++ b/test/fsendfile.c @@ -2,6 +2,39 @@ #include #include "check.h" +/* A failed read is an error, not EOF */ +static void read_error(void) +{ + int fd[2]; + ssize_t rc; + FILE *src; + + if (pipe(fd) || fcntl(fd[0], F_SETFL, O_NONBLOCK)) + err(1, "Failed creating nonblocking pipe"); + if (write(fd[1], "data", 4) != 4) + err(1, "Failed writing to pipe"); + + src = fdopen(fd[0], "r"); + if (!src) + err(1, "Failed fdopen()"); + + printf("fsendfile(pipe, NULL, 4)\t"); + rc = fsendfile(src, NULL, 4); + if (rc != 4) + errx(1, "Failed, got %zd, expected 4", rc); + printf("OK\n"); + + printf("fsendfile(empty pipe, NULL, 0)\t"); + errno = 0; + rc = fsendfile(src, NULL, 0); + if (rc != -1 || errno != EAGAIN) + errx(1, "Failed, got %zd errno %d, expected -1 and EAGAIN", rc, errno); + printf("OK\n"); + + fclose(src); + close(fd[1]); +} + int main(void) { int i = 0; @@ -27,5 +60,7 @@ int main(void) i += 2; } + read_error(); + return 0; }