From 38418fcd2bb0d6ae159fecbb527bfa02ea9c9c3e Mon Sep 17 00:00:00 2001 From: Richard Nyberg Date: Sun, 5 Feb 2006 11:34:18 +0000 Subject: Add functions read_fully and write_fully. They are simpler alternatives to read and write on blocking sockets. --- misc/subr.c | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) (limited to 'misc/subr.c') diff --git a/misc/subr.c b/misc/subr.c index 729d588..e16a7dc 100644 --- a/misc/subr.c +++ b/misc/subr.c @@ -174,3 +174,35 @@ rand_between(long min, long max) { return min + (long)rint((double)random() * (max - min) / RAND_MAX); } + +int +write_fully(int fd, const void *buf, size_t len) +{ + ssize_t nw; + size_t off = 0; + + while (off < len) { + nw = write(fd, buf + off, len - off); + if (nw == -1) + return errno; + off += nw; + } + return 0; +} + +int +read_fully(int fd, void *buf, size_t len) +{ + ssize_t nread; + size_t off = 0; + + while (off < len) { + nread = read(fd, buf + off, len - off); + if (nread == 0) + return ECONNRESET; + else if (nread == -1) + return errno; + off += nread; + } + return 0; +} -- cgit 1.4.1