mirror of
https://git.proxmox.com/git/proxmox
synced 2025-08-06 17:52:06 +00:00
tools: fd: improve drop handler and add some helpers
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
This commit is contained in:
parent
68f4a68bc1
commit
4a1c914827
@ -2,6 +2,10 @@
|
||||
|
||||
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
|
||||
|
||||
use nix::fcntl::OFlag;
|
||||
use nix::sys::stat::Mode;
|
||||
use nix::NixPath;
|
||||
|
||||
/// Guard a raw file descriptor with a drop handler. This is mostly useful when access to an owned
|
||||
/// `RawFd` is required without the corresponding handler object (such as when only the file
|
||||
/// descriptor number is required in a closure which may be dropped instead of being executed).
|
||||
@ -9,7 +13,8 @@ pub struct Fd(pub RawFd);
|
||||
|
||||
impl Drop for Fd {
|
||||
fn drop(&mut self) {
|
||||
if self.0 != -1 {
|
||||
// `>= 0` instead of `!= -1` to also handle things like AT_FDCWD
|
||||
if self.0 >= 0 {
|
||||
unsafe {
|
||||
libc::close(self.0);
|
||||
}
|
||||
@ -36,3 +41,24 @@ impl FromRawFd for Fd {
|
||||
Self(fd)
|
||||
}
|
||||
}
|
||||
|
||||
impl Fd {
|
||||
pub const fn cwd() -> Self {
|
||||
Self(libc::AT_FDCWD)
|
||||
}
|
||||
|
||||
pub fn open<P>(path: &P, oflag: OFlag, mode: Mode) -> Result<Self, nix::Error>
|
||||
where
|
||||
P: ?Sized + NixPath,
|
||||
{
|
||||
nix::fcntl::open(path, oflag, mode).map(Self)
|
||||
}
|
||||
|
||||
pub fn openat<D, P>(dirfd: D, path: &P, oflag: OFlag, mode: Mode) -> Result<Self, nix::Error>
|
||||
where
|
||||
D: AsRawFd,
|
||||
P: ?Sized + NixPath,
|
||||
{
|
||||
nix::fcntl::openat(dirfd.as_raw_fd(), path, oflag, mode).map(Self)
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user