Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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));
}