Skip to content

Commit

Permalink
Merge #1381
Browse files Browse the repository at this point in the history
1381: Close file descriptor on drop in TimerFd r=asomers a=crdumoul

This change closes the TimerFd file descriptor on drop. Note that the TimerFd will no longer be `Clone` or `Copy`. Since it has a destructor it can't be `Copy`, and if it were `Clone` you could end up trying to use a closed TimerFd, or double-closing the file descriptor.

Addresses #1379.

Co-authored-by: Christopher Dumoulin <cdumouli@akamai.com>
Co-authored-by: Alan Somers <asomers@gmail.com>
  • Loading branch information
3 people committed Feb 20, 2021
2 parents 661738c + 1bca805 commit c3320a0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ This project adheres to [Semantic Versioning](http://semver.org/).
### Changed

### Fixed
- `TimerFd` now closes the underlying fd on drop.
([#1381](https://github.com/nix-rust/nix/pull/1381))
- Define `*_MAGIC` filesystem constants on Linux s390x
(#[1372](https://github.com/nix-rust/nix/pull/1372))
- mqueue, sysinfo, timespec, statfs, test_ptrace_syscall() on x32
Expand All @@ -39,6 +41,8 @@ This project adheres to [Semantic Versioning](http://semver.org/).

- Removed `SockLevel`, which hasn't been used for a few years
(#[1362](https://github.com/nix-rust/nix/pull/1362))
- Removed both `Copy` and `Clone` from `TimerFd`.
([#1381](https://github.com/nix-rust/nix/pull/1381))

## [0.19.1] - 28 November 2020
### Fixed
Expand Down
17 changes: 15 additions & 2 deletions src/sys/timerfd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};

/// A timerfd instance. This is also a file descriptor, you can feed it to
/// other interfaces consuming file descriptors, epoll for example.
#[derive(Debug, Clone, Copy)]
#[derive(Debug)]
pub struct TimerFd {
fd: RawFd,
}
Expand Down Expand Up @@ -166,7 +166,7 @@ pub enum Expiration {
impl TimerFd {
/// Creates a new timer based on the clock defined by `clockid`. The
/// underlying fd can be assigned specific flags with `flags` (CLOEXEC,
/// NONBLOCK).
/// NONBLOCK). The underlying fd will be closed on drop.
pub fn new(clockid: ClockId, flags: TimerFlags) -> Result<Self> {
Errno::result(unsafe { libc::timerfd_create(clockid as i32, flags.bits()) })
.map(|fd| Self { fd })
Expand Down Expand Up @@ -270,3 +270,16 @@ impl TimerFd {
Ok(())
}
}

impl Drop for TimerFd {
fn drop(&mut self) {
if !std::thread::panicking() {
let result = Errno::result(unsafe {
libc::close(self.fd)
});
if let Err(Error::Sys(Errno::EBADF)) = result {
panic!("close of TimerFd encountered EBADF");
}
}
}
}

0 comments on commit c3320a0

Please sign in to comment.