Skip to content

Commit

Permalink
feat: clock_nanosleep() (nix-rust#2277)
Browse files Browse the repository at this point in the history
  • Loading branch information
SteveLauC authored Jan 7, 2024
1 parent 20db3f3 commit 0e8efe9
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog/2277.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add `clock_nanosleep()`
52 changes: 52 additions & 0 deletions src/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,3 +199,55 @@ pub fn clock_getcpuclockid(pid: Pid) -> Result<ClockId> {
Err(Errno::from_i32(ret))
}
}

#[cfg(any(
linux_android,
solarish,
freebsdlike,
target_os = "netbsd",
target_os = "hurd",
target_os = "aix"
))]
libc_bitflags! {
/// Flags that are used for arming the timer.
pub struct ClockNanosleepFlags: libc::c_int {
TIMER_ABSTIME;
}
}

/// Suspend execution of this thread for the amount of time specified by `request`
/// and measured against the clock speficied by `clock_id`. If `flags` is
/// `TIMER_ABSTIME`, this function will suspend execution until the time value of
/// clock_id reaches the absolute time specified by `request`. If a signal is caught
/// by a signal-catching function, or a signal causes the process to terminate,
/// this sleep is interrrupted.
///
/// see also [man 3 clock_nanosleep](https://pubs.opengroup.org/onlinepubs/009695399/functions/clock_nanosleep.html)
#[cfg(any(
linux_android,
solarish,
freebsdlike,
target_os = "netbsd",
target_os = "hurd",
target_os = "aix"
))]
pub fn clock_nanosleep(
clock_id: ClockId,
flags: ClockNanosleepFlags,
request: &TimeSpec,
) -> Result<TimeSpec> {
let mut remain = TimeSpec::new(0, 0);
let ret = unsafe {
libc::clock_nanosleep(
clock_id.as_raw(),
flags.bits(),
request.as_ref() as *const _,
remain.as_mut() as *mut _,
)
};
if ret == 0 {
Ok(remain)
} else {
Err(Errno::from_i32(ret))
}
}
25 changes: 25 additions & 0 deletions test/test_time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,28 @@ pub fn test_clock_id_pid_cpu_clock_id() {
.unwrap()
.unwrap();
}

#[cfg(any(
linux_android,
solarish,
freebsdlike,
target_os = "netbsd",
target_os = "hurd",
target_os = "aix"
))]
#[test]
pub fn test_clock_nanosleep() {
use nix::{
sys::time::{TimeSpec, TimeValLike},
time::{clock_nanosleep, ClockNanosleepFlags},
};

let sleep_time = TimeSpec::microseconds(1);
let res = clock_nanosleep(
ClockId::CLOCK_MONOTONIC,
ClockNanosleepFlags::empty(),
&sleep_time,
);
let expected = TimeSpec::microseconds(0);
assert_eq!(res, Ok(expected));
}

0 comments on commit 0e8efe9

Please sign in to comment.