Skip to content

Instantly share code, notes, and snippets.

@osa1
Created May 8, 2016 19:36
Show Gist options
  • Select an option

  • Save osa1/b86e3b1e392908496877b6acc5b8818a to your computer and use it in GitHub Desktop.

Select an option

Save osa1/b86e3b1e392908496877b6acc5b8818a to your computer and use it in GitHub Desktop.
use std::ops::Drop;
use std::os::unix::io::{AsRawFd, RawFd};
use std::ptr;
use std::time::Duration;
use libc;
extern {
/// int timerfd_create(int clockid, int flags)
fn timerfd_create(clockid : libc::c_int, flags : libc::c_int) -> libc::c_int;
/// int timerfd_settime(int fd, int flags,
/// const struct itimerspec *new_value,
/// struct itimerspec *old_value)
fn timerfd_settime(fd : libc::c_int, flags : libc::c_int,
new_value : *const libc::c_void,
old_value : *mut libc::c_void) -> libc::c_int;
/// int timerfd_gettime(int fd, struct itimerspec *curr_value);
fn timerfd_gettime(fd : libc::c_int, curr_value : *mut libc::c_void) -> libc::c_int;
}
pub struct TimerFd {
fd : RawFd,
}
pub enum ClockId {
ClockRealtime = libc::CLOCK_REALTIME as isize,
ClockMonotonic = libc::CLOCK_MONOTONIC as isize
}
#[repr(C)]
struct itimerspec {
it_interval : libc::timespec,
it_value : libc::timespec,
}
impl TimerFd {
pub fn new(clockid : ClockId) -> TimerFd {
TimerFd {
fd: unsafe { timerfd_create(clockid as libc::c_int, 0) }
}
}
pub fn set_time(&mut self, initial_expiration : Duration, interval : Duration) {
// TODO: Not sure about type coercions here
let timerspec = itimerspec {
it_interval:
libc::timespec {
tv_sec: interval.as_secs() as libc::time_t,
tv_nsec: interval.subsec_nanos() as libc::c_long,
},
it_value:
libc::timespec {
tv_sec: initial_expiration.as_secs() as libc::time_t,
tv_nsec: initial_expiration.subsec_nanos() as libc::c_long,
},
};
let ret = unsafe {
timerfd_settime(self.fd, 0,
(&timerspec as *const itimerspec) as *const libc::c_void,
ptr::null_mut())
};
assert_eq!(ret, 0);
}
}
impl Drop for TimerFd {
fn drop(&mut self) {
unsafe { libc::close(self.fd); }
}
}
impl AsRawFd for TimerFd {
fn as_raw_fd(&self) -> RawFd {
self.fd
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment