Skip to content

Commit 4e1100b

Browse files
committed
Add a try_clone method to OwnedFd.
This corresponds to the `try_clone` function in sunfishcode/io-lifetimes#16 and rust-lang/rust#88794.
1 parent 32b50d5 commit 4e1100b

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/io/owned_fd.rs

+21
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,27 @@ pub struct OwnedFd {
2727
inner: ManuallyDrop<crate::imp::fd::OwnedFd>,
2828
}
2929

30+
impl OwnedFd {
31+
/// Creates a new `OwnedFd` instance that shares the same underlying file handle
32+
/// as the existing `OwnedFd` instance.
33+
pub fn try_clone(&self) -> std::io::Result<Self> {
34+
// We want to atomically duplicate this file descriptor and set the
35+
// CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This
36+
// is a POSIX flag that was added to Linux in 2.6.24.
37+
#[cfg(not(target_os = "espidf"))]
38+
let fd = crate::fs::fcntl_dupfd_cloexec(self, 0)?;
39+
40+
// For ESP-IDF, F_DUPFD is used instead, because the CLOEXEC semantics
41+
// will never be supported, as this is a bare metal framework with
42+
// no capabilities for multi-process execution. While F_DUPFD is also
43+
// not supported yet, it might be (currently it returns ENOSYS).
44+
#[cfg(target_os = "espidf")]
45+
let fd = crate::fs::fcntl_dupfd(self)?;
46+
47+
Ok(fd)
48+
}
49+
}
50+
3051
#[cfg(not(windows))]
3152
impl AsFd for OwnedFd {
3253
#[inline]

0 commit comments

Comments
 (0)