Skip to content

Commit

Permalink
Enable CLOEXEC by default and allow it to be changed after creation.
Browse files Browse the repository at this point in the history
  • Loading branch information
de-vri-es committed Oct 8, 2020
1 parent fe2fea2 commit b8abef9
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/memfd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ impl Default for MemfdOptions {
fn default() -> Self {
Self {
allow_sealing: false,
cloexec: false,
cloexec: true,
hugetlb: None,
}
}
Expand Down
23 changes: 23 additions & 0 deletions tests/memfd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,19 @@ fn test_memfd_default() {
let meta0 = m0.as_file().metadata().unwrap();
assert_eq!(meta0.len(), 0);
assert_eq!(meta0.is_file(), true);
assert_eq!(get_close_on_exec(&m0).unwrap(), true);
drop(m0)
}

#[test]
fn test_memfd_no_cloexec() {
let memfd = memfd::MemfdOptions::default()
.close_on_exec(false)
.create("no-cloexec")
.unwrap();
assert_eq!(get_close_on_exec(&memfd).unwrap(), false);
}

#[test]
fn test_memfd_multi() {
let opts = memfd::MemfdOptions::default();
Expand Down Expand Up @@ -40,3 +50,16 @@ fn test_memfd_from_into() {
.right()
.expect("unexpected conversion from a non-memfd file");
}

/// Check if the close-on-exec flag is set for the memfd.
pub fn get_close_on_exec(memfd: &memfd::Memfd) -> std::io::Result<bool> {
// SAFETY: The syscall called has no soundness implications (i.e. does not mess with
// process memory in weird ways, checks its arguments for correctness, etc.). Furthermore
// due to invariants of `Memfd` this syscall is provided a valid file descriptor.
let flags = unsafe { libc::fcntl(memfd.as_file().as_raw_fd(), libc::F_GETFD, 0) };
if flags == -1 {
Err(std::io::Error::last_os_error())
} else {
Ok(flags & libc::FD_CLOEXEC != 0)
}
}

0 comments on commit b8abef9

Please sign in to comment.