Skip to content

Commit aea3eeb

Browse files
committed
Add Socket::set_cloexec
1 parent 4ba334f commit aea3eeb

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/sys/unix.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,28 @@ pub(crate) fn socket(family: c_int, ty: c_int, protocol: c_int) -> io::Result<Sy
245245
syscall!(socket(family, ty, protocol))
246246
}
247247

248+
impl crate::Socket {
249+
/// Sets `CLOEXEC` on the socket.
250+
///
251+
/// # Notes
252+
///
253+
/// On supported platforms you can use [`Protocol::cloexec`].
254+
pub fn set_cloexec(&self) -> io::Result<()> {
255+
fcntl_add(self.inner, libc::FD_CLOEXEC)
256+
}
257+
}
258+
259+
fn fcntl_add(fd: SysSocket, flag: c_int) -> io::Result<()> {
260+
let previous = syscall!(fcntl(fd, libc::F_GETFD))?;
261+
let new = previous | flag;
262+
if new != previous {
263+
syscall!(fcntl(fd, libc::F_SETFD, new)).map(|_| ())
264+
} else {
265+
// Flag was already set.
266+
Ok(())
267+
}
268+
}
269+
248270
#[repr(transparent)] // Required during rewriting.
249271
pub struct Socket {
250272
fd: SysSocket,

0 commit comments

Comments
 (0)