about summary refs log tree commit diff
path: root/src/libutil
diff options
context:
space:
mode:
Diffstat (limited to 'src/libutil')
-rw-r--r--src/libutil/util.cc23
-rw-r--r--src/libutil/util.hh4
2 files changed, 22 insertions, 5 deletions
diff --git a/src/libutil/util.cc b/src/libutil/util.cc
index 764b4e44207e..ab2d097f8b62 100644
--- a/src/libutil/util.cc
+++ b/src/libutil/util.cc
@@ -567,21 +567,38 @@ void writeFull(int fd, const string & s, bool allowInterrupts)
 }
 
 
-string drainFD(int fd)
+string drainFD(int fd, bool block)
 {
     StringSink sink;
-    drainFD(fd, sink);
+    drainFD(fd, sink, block);
     return std::move(*sink.s);
 }
 
 
-void drainFD(int fd, Sink & sink)
+void drainFD(int fd, Sink & sink, bool block)
 {
+    int saved;
+
+    Finally finally([&]() {
+        if (!block) {
+            if (fcntl(fd, F_SETFL, saved) == -1)
+                throw SysError("making file descriptor blocking");
+        }
+    });
+
+    if (!block) {
+        saved = fcntl(fd, F_GETFL);
+        if (fcntl(fd, F_SETFL, saved | O_NONBLOCK) == -1)
+            throw SysError("making file descriptor non-blocking");
+    }
+
     std::vector<unsigned char> buf(4096);
     while (1) {
         checkInterrupt();
         ssize_t rd = read(fd, buf.data(), buf.size());
         if (rd == -1) {
+            if (!block && (errno == EAGAIN || errno == EWOULDBLOCK))
+                break;
             if (errno != EINTR)
                 throw SysError("reading from file");
         }
diff --git a/src/libutil/util.hh b/src/libutil/util.hh
index 85952535db29..743d238611fc 100644
--- a/src/libutil/util.hh
+++ b/src/libutil/util.hh
@@ -151,9 +151,9 @@ MakeError(EndOfFile, Error)
 
 
 /* Read a file descriptor until EOF occurs. */
-string drainFD(int fd);
+string drainFD(int fd, bool block = true);
 
-void drainFD(int fd, Sink & sink);
+void drainFD(int fd, Sink & sink, bool block = true);
 
 
 /* Automatic cleanup of resources. */