Skip to content

Commit 4be1dfb

Browse files
committed
Make TCP connect handle EINTR correctly
According to the POSIX standart, if connect() is interrupted by a signal that is caught while blocked waiting to establish a connection, connect() shall fail and set errno to EINTR, but the connection request shall not be aborted, and the connection shall be established asynchronously. When the connection has been established asynchronously, select() and poll() shall indicate that the file descriptor for the socket is ready for writing. The previous implementation differs from the recomendation: in a case of the EINTR we tried to reconnect in a loop and sometimes get EISCONN error (this problem was originally detected on MacOS).
1 parent 42ca6e4 commit 4be1dfb

File tree

1 file changed

+22
-1
lines changed
  • library/std/src/sys_common

1 file changed

+22
-1
lines changed

library/std/src/sys_common/net.rs

+22-1
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,28 @@ impl TcpStream {
228228
let sock = Socket::new(addr, c::SOCK_STREAM)?;
229229

230230
let (addr, len) = addr.into_inner();
231-
cvt_r(|| unsafe { c::connect(sock.as_raw(), addr.as_ptr(), len) })?;
231+
232+
let ret = unsafe { c::connect(sock.as_raw(), addr.as_ptr(), len) };
233+
if ret < 0 {
234+
let err = io::Error::last_os_error();
235+
if !err.is_interrupted() {
236+
return Err(err);
237+
}
238+
239+
let mut pollfd = libc::pollfd { fd: sock.as_raw(), events: libc::POLLOUT, revents: 0 };
240+
loop {
241+
let ret = unsafe { libc::poll(&mut pollfd, 1, -1) };
242+
if ret < 0 {
243+
let err = io::Error::last_os_error();
244+
if err.is_interrupted() {
245+
continue;
246+
}
247+
return Err(err);
248+
}
249+
break;
250+
}
251+
sock.take_error()?;
252+
}
232253
Ok(TcpStream { inner: sock })
233254
}
234255

0 commit comments

Comments
 (0)