Don't spin on empty fds in `read2` on Unix
authorAlex Crichton <alex@alexcrichton.com>
Mon, 12 Feb 2018 17:27:11 +0000 (09:27 -0800)
committerAlex Crichton <alex@alexcrichton.com>
Mon, 12 Feb 2018 17:27:11 +0000 (09:27 -0800)
This commit fixes what I think is some pathological behavior in Cargo where if
one stdio stream is closed before another then Cargo can accidentally spin in a
tight loop and not block appropriately. Previously, for example, if stderr
closed before stdout then Cargo would spin in a `poll` loop continuously getting
notified that stderr is closed.

The behavior is now changed so after a file descriptor is done we stop passing
it to `poll` and instead only pass the one remaining readable file descriptor.

src/cargo/util/read2.rs

index 74d6d67f271e5d3037c3c16f2b86abb63828533b..7b2681082968c96d3034bbcad9998d3d6ea0605c 100644 (file)
@@ -27,9 +27,12 @@ mod imp {
         fds[0].events = libc::POLLIN;
         fds[1].fd = err_pipe.as_raw_fd();
         fds[1].events = libc::POLLIN;
-        loop {
+        let mut nfds = 2;
+        let mut errfd = 1;
+
+        while nfds > 0 {
             // wait for either pipe to become readable using `select`
-            let r = unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) };
+            let r = unsafe { libc::poll(fds.as_mut_ptr(), nfds, -1) };
             if r == -1 {
                 let err = io::Error::last_os_error();
                 if err.kind() == io::ErrorKind::Interrupted {
@@ -55,19 +58,20 @@ mod imp {
                     }
                 }
             };
-            if !out_done && fds[0].revents != 0 && handle(out_pipe.read_to_end(&mut out))? {
-                out_done = true;
-            }
-            data(true, &mut out, out_done);
-            if !err_done && fds[1].revents != 0 && handle(err_pipe.read_to_end(&mut err))? {
+            if !err_done && fds[errfd].revents != 0 && handle(err_pipe.read_to_end(&mut err))? {
                 err_done = true;
+                nfds -= 1;
             }
             data(false, &mut err, err_done);
-
-            if out_done && err_done {
-                return Ok(())
+            if !out_done && fds[0].revents != 0 && handle(out_pipe.read_to_end(&mut out))? {
+                out_done = true;
+                fds[0].fd = err_pipe.as_raw_fd();
+                errfd = 0;
+                nfds -= 1;
             }
+            data(true, &mut out, out_done);
         }
+        Ok(())
     }
 }