]> git.proxmox.com Git - proxmox.git/commitdiff
proxmox: add fd_change_cloexec
authorDietmar Maurer <dietmar@proxmox.com>
Thu, 18 Nov 2021 12:06:34 +0000 (13:06 +0100)
committerDietmar Maurer <dietmar@proxmox.com>
Thu, 18 Nov 2021 12:06:34 +0000 (13:06 +0100)
proxmox/src/tools/fd.rs

index e13172d5b13617713cc5652fe00440a693003d1e..582f884fbb3270bcf8dc7a6895b5959ca3518935 100644 (file)
@@ -7,6 +7,7 @@ use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
 use nix::fcntl::OFlag;
 use nix::sys::stat::Mode;
 use nix::NixPath;
+use nix::fcntl::{fcntl, FdFlag, F_GETFD, F_SETFD};
 
 /// Guard a raw file descriptor with a drop handler. This is mostly useful when access to an owned
 /// `RawFd` is required without the corresponding handler object (such as when only the file
@@ -194,3 +195,11 @@ impl<'a, T: ?Sized + AsRawFd> From<&'a T> for BorrowedFd<'a> {
         Self::new(fd)
     }
 }
+
+/// Change the `O_CLOEXEC` flag of an existing file descriptor.
+pub fn fd_change_cloexec(fd: RawFd, on: bool) -> Result<(), anyhow::Error> {
+    let mut flags = unsafe { FdFlag::from_bits_unchecked(fcntl(fd, F_GETFD)?) };
+    flags.set(FdFlag::FD_CLOEXEC, on);
+    fcntl(fd, F_SETFD(flags))?;
+    Ok(())
+}