Adds saferead() and safewrite(), which are like read() and write()
except that they retry in case of EINTR.
Signed-off-by: Jim Paris <jim(a)jtan.com>
---
src/util.c | 37 +++++++++++++++++++++++++++++++++++++
src/util.h | 2 ++
2 files changed, 39 insertions(+), 0 deletions(-)
diff --git a/src/util.c b/src/util.c
index 4f80eef..eb57859 100644
--- a/src/util.c
+++ b/src/util.c
@@ -189,3 +189,40 @@ virExecNonBlock(virConnectPtr conn,
return(_virExec(conn, argv, retpid, infd, outfd, errfd, 1));
}
+/* Like read(), but restarts after EINTR */
+int saferead(int fd, void *buf, size_t count)
+{
+ size_t nread = 0;
+ while (count > 0) {
+ int r = read(fd, buf, count);
+ if (r < 0 && errno == EINTR)
+ continue;
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return nread;
+ buf = (unsigned char *)buf + r;
+ count -= r;
+ nread += r;
+ }
+ return nread;
+}
+
+/* Like write(), but restarts after EINTR */
+ssize_t safewrite(int fd, const void *buf, size_t count)
+{
+ size_t nwritten = 0;
+ while (count > 0) {
+ int r = write(fd, buf, count);
+ if (r < 0 && errno == EINTR)
+ continue;
+ if (r < 0)
+ return r;
+ if (r == 0)
+ return nwritten;
+ buf = (unsigned char *)buf + r;
+ count -= r;
+ nwritten += r;
+ }
+ return nwritten;
+}
diff --git a/src/util.h b/src/util.h
index d11e6d9..f69fac8 100644
--- a/src/util.h
+++ b/src/util.h
@@ -24,3 +24,5 @@
int virExec(virConnectPtr conn, char **argv, int *retpid, int infd, int *outfd, int
*errfd);
int virExecNonBlock(virConnectPtr conn, char **argv, int *retpid, int infd, int *outfd,
int *errfd);
+int saferead(int fd, void *buf, size_t count);
+ssize_t safewrite(int fd, const void *buf, size_t count);
--
1.5.3.rc4