From 945e83a6baa2bdf207650a66f8e84da6889052ed Mon Sep 17 00:00:00 2001 From: Konstantin Knizhnik Date: Wed, 15 Dec 2021 00:05:26 +0300 Subject: [PATCH] Add nonblock.rs --- zenith_utils/src/nonblock.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 zenith_utils/src/nonblock.rs diff --git a/zenith_utils/src/nonblock.rs b/zenith_utils/src/nonblock.rs new file mode 100644 index 0000000000..8b1fd71ae6 --- /dev/null +++ b/zenith_utils/src/nonblock.rs @@ -0,0 +1,17 @@ +use nix::fcntl::{fcntl, OFlag, F_GETFL, F_SETFL}; +use std::os::unix::io::RawFd; + +/// Put a file descriptor into non-blocking mode +pub fn set_nonblock(fd: RawFd) -> Result<(), std::io::Error> { + let bits = fcntl(fd, F_GETFL)?; + + // Safety: If F_GETFL returns some unknown bits, they should be valid + // for passing back to F_SETFL, too. If we left them out, the F_SETFL + // would effectively clear them, which is not what we want. + let mut flags = unsafe { OFlag::from_bits_unchecked(bits) }; + flags |= OFlag::O_NONBLOCK; + + fcntl(fd, F_SETFL(flags))?; + + Ok(()) +}