use std::io;
#[allow(unused)]
pub trait Nonblocking {
fn get_nonblocking(&self) -> io::Result<bool>;
fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()>;
}
impl Nonblocking for std::fs::File {
fn get_nonblocking(&self) -> io::Result<bool> {
use nix::fcntl::{fcntl, FcntlArg, OFlag};
use std::os::unix::io::AsRawFd;
let fd = self.as_raw_fd();
let raw_flags = fcntl(fd, FcntlArg::F_GETFL)?;
let flags = OFlag::from_bits_truncate(raw_flags);
Ok(flags.contains(OFlag::O_NONBLOCK))
}
fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
use nix::fcntl::{fcntl, FcntlArg, OFlag};
use std::os::unix::io::AsRawFd;
let fd = self.as_raw_fd();
let raw_flags = fcntl(fd, FcntlArg::F_GETFL)?;
let mut flags = OFlag::from_bits_truncate(raw_flags);
if nonblocking {
flags.insert(OFlag::O_NONBLOCK);
} else {
flags.remove(OFlag::O_NONBLOCK);
}
fcntl(fd, FcntlArg::F_SETFL(flags))?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use anyhow::Result;
use nix::unistd::pipe;
use std::io::Read;
#[test]
fn get_nonblocking_works() -> Result<()> {
let (rfd, _wfd) = pipe().unwrap();
let rfile = std::fs::File::from(rfd);
assert!(!rfile.get_nonblocking()?);
Ok(())
}
#[test]
fn set_nonblocking_works() -> Result<()> {
let (rfd, _wfd) = pipe().unwrap();
let rfile = std::fs::File::from(rfd);
assert!(!rfile.get_nonblocking()?);
rfile.set_nonblocking(true)?;
assert!(rfile.get_nonblocking()?);
Ok(())
}
#[test]
fn set_nonblocking_has_effect() -> Result<()> {
let (rfd, _wfd) = pipe().unwrap();
let mut rfile = std::fs::File::from(rfd);
rfile.set_nonblocking(true)?;
let mut buf = [0u8; 80];
let err = rfile.read(&mut buf).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::WouldBlock);
Ok(())
}
}
¤ Dauer der Verarbeitung: 0.6 Sekunden
¤
*© Formatika GbR, Deutschland