Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow invoking fsync #20

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 37 additions & 3 deletions src/dir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use {Dir, AsPath};
const BASE_OPEN_FLAGS: libc::c_int = libc::O_CLOEXEC;
#[cfg(not(target_os="macos"))]
const BASE_OPEN_FLAGS: libc::c_int = libc::O_PATH|libc::O_CLOEXEC;
const FULL_OPEN_FLAGS: libc::c_int = libc::O_CLOEXEC;

impl Dir {
/// Creates a directory descriptor that resolves paths relative to current
Expand All @@ -34,12 +35,18 @@ impl Dir {
/// Open a directory descriptor at specified path
// TODO(tailhook) maybe accept only absolute paths?
pub fn open<P: AsPath>(path: P) -> io::Result<Dir> {
Dir::_open(to_cstr(path)?.as_ref())
Dir::_open(to_cstr(path)?.as_ref(), BASE_OPEN_FLAGS)
}

fn _open(path: &CStr) -> io::Result<Dir> {
/// Open a directory descriptor at specified path with full
/// file operations.
pub fn open_full<P: AsPath>(path: P) -> io::Result<Dir> {
Dir::_open(to_cstr(path)?.as_ref(), FULL_OPEN_FLAGS)
}

fn _open(path: &CStr, flags: libc::c_int) -> io::Result<Dir> {
let fd = unsafe {
libc::open(path.as_ptr(), BASE_OPEN_FLAGS)
libc::open(path.as_ptr(), flags)
};
if fd < 0 {
Err(io::Error::last_os_error())
Expand Down Expand Up @@ -397,6 +404,16 @@ impl Dir {
}
}
}

/// Sync directory metadata.
pub fn sync_all(&self) -> io::Result<()> {
let res = unsafe { libc::fsync(self.0) };
if res == -1 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
}

/// Rename (move) a file between directories
Expand Down Expand Up @@ -585,4 +602,21 @@ mod test {
})
.is_some());
}

#[test]
#[cfg(target_os="linux")]
#[should_panic(expected="Bad file descriptor")]
fn test_sync_base_fail() {
/* A lightweight fd obtained with `O_PATH` lacks file operations. */
let dir = Dir::open("src").unwrap();
dir.sync_all().unwrap();
}

#[test]
#[cfg(target_os="linux")]
fn test_sync_full_ok() {
/* A regular fd can be fsync(2)ed. */
let dir = Dir::open_full("src").unwrap();
assert!(dir.sync_all().is_ok());
}
}