Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix read_all() and write_all() to always set errno on failure #86

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 18 additions & 8 deletions ccan/read_write_all/read_write_all.c
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@ bool write_all(int fd, const void *data, size_t size)
ssize_t done;

done = write(fd, data, size);
if (done < 0 && errno == EINTR)
continue;
if (done <= 0)
if (done < 0) {
if (errno == EINTR) {
continue;
}
return false;
}
data = (const char *)data + done;
size -= done;
}
Expand All @@ -26,12 +28,20 @@ bool read_all(int fd, void *data, size_t size)
ssize_t done;

done = read(fd, data, size);
if (done < 0 && errno == EINTR)
continue;
if (done <= 0)

switch (done) {
case -1:
if (errno == EINTR) {
continue;
}
return false;
data = (char *)data + done;
size -= done;
case 0:
errno = EBADMSG;
return false;
default:
data = (char *)data + done;
size -= done;
}
}

return true;
Expand Down
14 changes: 14 additions & 0 deletions ccan/read_write_all/read_write_all.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,21 @@
#include <stddef.h>
#include <stdbool.h>

/**
* Write `size` bytes from `data` to the file descriptor `fd`, retrying on
* transient errors.
* If the data cannot be fully written, then false is returned and errno is set
* to indicate the error.
*/
bool write_all(int fd, const void *data, size_t size);

/**
* Read `size` bytes from the file descriptor `fd` into `data`, retrying on
* transient errors.
* If `size` bytes cannot be read then false is returned and errno is set
* to indicate the error, in which case the contents of `data` is undefined.
* If EOF occurs before `size` bytes were read, then errno is set to EBADMSG.
*/
bool read_all(int fd, void *data, size_t size);

#endif /* _CCAN_READ_WRITE_H */