#![allow(unsafe_code)]
use std::fs::File;
use std::io;
use std::os::fd::{AsRawFd, BorrowedFd, FromRawFd, OwnedFd, RawFd};
const COPY_ABOVE: libc::c_int = 10;
pub(super) fn check_open(fd: RawFd) -> io::Result<()> {
if unsafe { libc::fcntl(fd, libc::F_GETFD) } < 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
pub(super) fn take(fd: RawFd) -> io::Result<OwnedFd> {
let copy = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, COPY_ABOVE) };
if copy < 0 {
return Err(io::Error::last_os_error());
}
let copy = unsafe { OwnedFd::from_raw_fd(copy) };
let null = File::options().read(true).write(true).open("/dev/null")?;
if unsafe { libc::dup2(null.as_raw_fd(), fd) } < 0 {
return Err(io::Error::last_os_error());
}
Ok(copy)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Ready {
pub(super) input: bool,
pub(super) woken: bool,
}
pub(super) fn poll(input: BorrowedFd<'_>, wake: BorrowedFd<'_>, block: bool) -> io::Result<Ready> {
let mut fds = [
libc::pollfd {
fd: input.as_raw_fd(),
events: libc::POLLIN,
revents: 0,
},
libc::pollfd {
fd: wake.as_raw_fd(),
events: libc::POLLIN,
revents: 0,
},
];
let timeout = if block { -1 } else { 0 };
loop {
let found = unsafe { libc::poll(fds.as_mut_ptr(), 2, timeout) };
if found >= 0 {
return Ok(Ready {
input: fds[0].revents != 0,
woken: fds[1].revents != 0,
});
}
let error = io::Error::last_os_error();
if error.kind() != io::ErrorKind::Interrupted {
return Err(error);
}
}
}