Module nix::unistd::alarm

source ·
Expand description

Alarm signal scheduling.

Scheduling an alarm will trigger a SIGALRM signal when the time has elapsed, which has to be caught, because the default action for the signal is to terminate the program. This signal also can’t be ignored because the system calls like pause will not be interrupted, see the second example below.

§Examples

Canceling an alarm:

use nix::unistd::alarm;

// Set an alarm for 60 seconds from now.
alarm::set(60);

// Cancel the above set alarm, which returns the number of seconds left
// of the previously set alarm.
assert_eq!(alarm::cancel(), Some(60));

Scheduling an alarm and waiting for the signal:

use std::time::{Duration, Instant};

use nix::unistd::{alarm, pause};
use nix::sys::signal::*;

// We need to setup an empty signal handler to catch the alarm signal,
// otherwise the program will be terminated once the signal is delivered.
extern fn signal_handler(_: nix::libc::c_int) { }
let sa = SigAction::new(
    SigHandler::Handler(signal_handler),
    SaFlags::SA_RESTART,
    SigSet::empty()
);
unsafe {
    sigaction(Signal::SIGALRM, &sa);
}

let start = Instant::now();

// Set an alarm for 1 second from now.
alarm::set(1);

// Pause the process until the alarm signal is received.
let mut sigset = SigSet::empty();
sigset.add(Signal::SIGALRM);
sigset.wait();

assert!(start.elapsed() >= Duration::from_secs(1));

§References

See also alarm(2).

Functions§

  • Cancel an previously set alarm signal.
  • Schedule an alarm signal.