use std::io;
use std::os::fd::{AsRawFd, BorrowedFd, RawFd};
use nix::fcntl::{FcntlArg, FdFlag, fcntl};
#[allow(
dead_code,
reason = "exercised by this module's own tests; production goes through \
`keep_raw_across_exec`, which a blob's numbers are all it has"
)]
pub fn keep_across_exec(fd: BorrowedFd<'_>) -> io::Result<()> {
keep_raw_across_exec(fd.as_raw_fd())
}
pub fn keep_raw_across_exec(fd: RawFd) -> io::Result<()> {
let flags = fcntl(fd, FcntlArg::F_GETFD)?;
let mut flags = FdFlag::from_bits_truncate(flags);
flags.remove(FdFlag::FD_CLOEXEC);
fcntl(fd, FcntlArg::F_SETFD(flags))?;
Ok(())
}
pub fn close_raw_after_exec(fd: RawFd) -> io::Result<()> {
let flags = fcntl(fd, FcntlArg::F_GETFD)?;
let mut flags = FdFlag::from_bits_truncate(flags);
flags.insert(FdFlag::FD_CLOEXEC);
fcntl(fd, FcntlArg::F_SETFD(flags))?;
Ok(())
}
pub fn duplicate_raw(fd: RawFd) -> io::Result<RawFd> {
Ok(fcntl(
fd,
FcntlArg::F_DUPFD_CLOEXEC(crate::sys::RESERVED_FD_FLOOR),
)?)
}
#[allow(dead_code, reason = "read by this module's own tests")]
pub fn is_kept(fd: BorrowedFd<'_>) -> io::Result<bool> {
let flags = fcntl(fd.as_raw_fd(), FcntlArg::F_GETFD)?;
let flags = FdFlag::from_bits_truncate(flags);
Ok(!flags.contains(FdFlag::FD_CLOEXEC))
}
#[cfg(test)]
mod tests {
use std::os::fd::AsFd;
#[test]
fn a_fresh_pipe_is_close_on_exec_and_can_be_kept() {
let (r, _w) = std::io::pipe().unwrap();
assert!(
!super::is_kept(r.as_fd()).unwrap(),
"std pipes are CLOEXEC by default"
);
super::keep_across_exec(r.as_fd()).unwrap();
assert!(super::is_kept(r.as_fd()).unwrap());
}
#[test]
fn keeping_is_idempotent() {
let (r, _w) = std::io::pipe().unwrap();
super::keep_across_exec(r.as_fd()).unwrap();
super::keep_across_exec(r.as_fd()).unwrap();
assert!(super::is_kept(r.as_fd()).unwrap());
}
}