Skip to content

Commit cb30fba

Browse files
committed
Auto merge of #5030 - alexcrichton:better-poll, r=matklad
Don't spin on empty fds in `read2` on Unix 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.
2 parents 43a62ba + ec991eb commit cb30fba

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

src/cargo/util/read2.rs

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,12 @@ mod imp {
2727
fds[0].events = libc::POLLIN;
2828
fds[1].fd = err_pipe.as_raw_fd();
2929
fds[1].events = libc::POLLIN;
30-
loop {
30+
let mut nfds = 2;
31+
let mut errfd = 1;
32+
33+
while nfds > 0 {
3134
// wait for either pipe to become readable using `select`
32-
let r = unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) };
35+
let r = unsafe { libc::poll(fds.as_mut_ptr(), nfds, -1) };
3336
if r == -1 {
3437
let err = io::Error::last_os_error();
3538
if err.kind() == io::ErrorKind::Interrupted {
@@ -55,19 +58,20 @@ mod imp {
5558
}
5659
}
5760
};
58-
if !out_done && fds[0].revents != 0 && handle(out_pipe.read_to_end(&mut out))? {
59-
out_done = true;
60-
}
61-
data(true, &mut out, out_done);
62-
if !err_done && fds[1].revents != 0 && handle(err_pipe.read_to_end(&mut err))? {
61+
if !err_done && fds[errfd].revents != 0 && handle(err_pipe.read_to_end(&mut err))? {
6362
err_done = true;
63+
nfds -= 1;
6464
}
6565
data(false, &mut err, err_done);
66-
67-
if out_done && err_done {
68-
return Ok(())
66+
if !out_done && fds[0].revents != 0 && handle(out_pipe.read_to_end(&mut out))? {
67+
out_done = true;
68+
fds[0].fd = err_pipe.as_raw_fd();
69+
errfd = 0;
70+
nfds -= 1;
6971
}
72+
data(true, &mut out, out_done);
7073
}
74+
Ok(())
7175
}
7276
}
7377

0 commit comments

Comments
 (0)