From b4056f6c96e0db54db7fa6241f85c42587b2e06b Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 19 May 2019 10:49:09 -0700 Subject: [PATCH] potentially support atomic dup on linux I'm testing this under WSL which doesn't seem to support it, so I'm committing this so I can try it on a real linux system. --- filedescriptor/src/unix.rs | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index eb692e342..5863139e6 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -76,9 +76,7 @@ impl OwnedHandle { Ok(()) } - #[inline] - pub(crate) fn dup_impl(fd: &F) -> Fallible { - let fd = fd.as_raw_file_descriptor(); + fn non_atomic_dup(fd: RawFd) -> Fallible { let duped = unsafe { libc::dup(fd) }; if duped == -1 { bail!( @@ -92,6 +90,32 @@ impl OwnedHandle { Ok(owned) } } + + #[inline] + #[cfg(not(target_os = "linux"))] + pub(crate) fn dup_impl(fd: &F) -> Fallible { + let fd = fd.as_raw_file_descriptor(); + Self::non_atomic_dup(fd) + } + + #[inline] + #[cfg(target_os = "linux")] + pub(crate) fn dup_impl(fd: &F) -> Fallible { + let fd = fd.as_raw_file_descriptor(); + let duped = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC) }; + if duped == -1 { + let err = std::io::Error::last_os_error(); + if let Some(libc::EINVAL) = err.raw_os_error() { + // We may be running on eg: WSL or an old kernel that + // doesn't support F_DUPFD_CLOEXEC; fall back. + return Self::non_atomic_dup(fd); + } else { + bail!("dup of fd {} failed: {:?}", fd, err) + } + } else { + Ok(OwnedHandle { handle: duped }) + } + } } impl std::io::Read for FileDescriptor {