Skip to content

Commit efeb42b

Browse files
committed
Use less syscalls in FileDesc::set_{nonblocking,cloexec}
Only set the flags if they differ from what the OS reported, use `FIONBIO` to atomically set the non-blocking IO flag on Linux.
1 parent 86d9ed6 commit efeb42b

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

Diff for: src/libstd/sys/unix/fd.rs

+17-2
Original file line numberDiff line numberDiff line change
@@ -144,11 +144,24 @@ impl FileDesc {
144144
pub fn set_cloexec(&self) -> io::Result<()> {
145145
unsafe {
146146
let previous = cvt(libc::fcntl(self.fd, libc::F_GETFD))?;
147-
cvt(libc::fcntl(self.fd, libc::F_SETFD, previous | libc::FD_CLOEXEC))?;
147+
let new = previous | libc::FD_CLOEXEC;
148+
if new != previous {
149+
cvt(libc::fcntl(self.fd, libc::F_SETFD, new))?;
150+
}
151+
Ok(())
152+
}
153+
}
154+
155+
#[cfg(target_os = "linux")]
156+
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
157+
unsafe {
158+
let v = nonblocking as c_int;
159+
cvt(libc::ioctl(self.fd, libc::FIONBIO, &v))?;
148160
Ok(())
149161
}
150162
}
151163

164+
#[cfg(not(target_os = "linux"))]
152165
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
153166
unsafe {
154167
let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?;
@@ -157,7 +170,9 @@ impl FileDesc {
157170
} else {
158171
previous & !libc::O_NONBLOCK
159172
};
160-
cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?;
173+
if new != previous {
174+
cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?;
175+
}
161176
Ok(())
162177
}
163178
}

0 commit comments

Comments
 (0)