Skip to content

Commit c3320a0

Browse files
bors[bot]cdumouliasomers
authored
Merge #1381
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 <[email protected]> Co-authored-by: Alan Somers <[email protected]>
2 parents 661738c + 1bca805 commit c3320a0

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

CHANGELOG.md

+4
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ This project adheres to [Semantic Versioning](http://semver.org/).
1616
### Changed
1717

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

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

4347
## [0.19.1] - 28 November 2020
4448
### Fixed

src/sys/timerfd.rs

+15-2
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
3737

3838
/// A timerfd instance. This is also a file descriptor, you can feed it to
3939
/// other interfaces consuming file descriptors, epoll for example.
40-
#[derive(Debug, Clone, Copy)]
40+
#[derive(Debug)]
4141
pub struct TimerFd {
4242
fd: RawFd,
4343
}
@@ -166,7 +166,7 @@ pub enum Expiration {
166166
impl TimerFd {
167167
/// Creates a new timer based on the clock defined by `clockid`. The
168168
/// underlying fd can be assigned specific flags with `flags` (CLOEXEC,
169-
/// NONBLOCK).
169+
/// NONBLOCK). The underlying fd will be closed on drop.
170170
pub fn new(clockid: ClockId, flags: TimerFlags) -> Result<Self> {
171171
Errno::result(unsafe { libc::timerfd_create(clockid as i32, flags.bits()) })
172172
.map(|fd| Self { fd })
@@ -270,3 +270,16 @@ impl TimerFd {
270270
Ok(())
271271
}
272272
}
273+
274+
impl Drop for TimerFd {
275+
fn drop(&mut self) {
276+
if !std::thread::panicking() {
277+
let result = Errno::result(unsafe {
278+
libc::close(self.fd)
279+
});
280+
if let Err(Error::Sys(Errno::EBADF)) = result {
281+
panic!("close of TimerFd encountered EBADF");
282+
}
283+
}
284+
}
285+
}

0 commit comments

Comments
 (0)