tools: add socketpair helper

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
This commit is contained in:
Wolfgang Bumiller 2020-06-22 10:49:56 +02:00
parent dc2ef2b54f
commit c40440092d
1 changed files with 16 additions and 1 deletions

View File

@ -553,12 +553,27 @@ pub fn fail_on_shutdown() -> Result<(), Error> {
Ok(()) Ok(())
} }
// wrap nix::unistd::pipe2 + O_CLOEXEC into something returning guarded file descriptors /// safe wrapper for `nix::unistd::pipe2` defaulting to `O_CLOEXEC` and guarding the file
/// descriptors.
pub fn pipe() -> Result<(Fd, Fd), Error> { pub fn pipe() -> Result<(Fd, Fd), Error> {
let (pin, pout) = nix::unistd::pipe2(nix::fcntl::OFlag::O_CLOEXEC)?; let (pin, pout) = nix::unistd::pipe2(nix::fcntl::OFlag::O_CLOEXEC)?;
Ok((Fd(pin), Fd(pout))) Ok((Fd(pin), Fd(pout)))
} }
/// safe wrapper for `nix::sys::socket::socketpair` defaulting to `O_CLOEXEC` and guarding the file
/// descriptors.
pub fn socketpair() -> Result<(Fd, Fd), Error> {
use nix::sys::socket;
let (pa, pb) = socket::socketpair(
socket::AddressFamily::Unix,
socket::SockType::Stream,
None,
socket::SockFlag::SOCK_CLOEXEC,
)?;
Ok((Fd(pa), Fd(pb)))
}
/// An easy way to convert types to Any /// An easy way to convert types to Any
/// ///
/// Mostly useful to downcast trait objects (see RpcEnvironment). /// Mostly useful to downcast trait objects (see RpcEnvironment).