1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
// Copyright (c) 2015 CtrlC developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.

//! A simple easy to use wrapper around Ctrl-C.
//! # Example
//! ```no_run
//! extern crate ctrlc;
//! use std::sync::atomic::{AtomicBool, Ordering};
//! use std::sync::Arc;
//!
//! fn main() {
//!     let running = Arc::new(AtomicBool::new(true));
//!     let r = running.clone();
//!     ctrlc::set_handler(move || {
//!         r.store(false, Ordering::SeqCst);
//!     });
//!     println!("Waiting for Ctrl-C...");
//!     while running.load(Ordering::SeqCst) {}
//!     println!("Got it! Exiting...");
//! }
//! ```

use std::sync::atomic::Ordering;
use std::thread;
use std::time;

use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT};
static DONE: AtomicBool = ATOMIC_BOOL_INIT;

#[cfg(unix)]
mod platform {
    extern crate libc;
    use self::libc::c_int;
    use self::libc::sighandler_t;
    use self::libc::SIGINT;

    #[cfg(feature = "termination")]
    use self::libc::SIGTERM;

    use self::libc::signal;
    use std::sync::atomic::Ordering;

    pub fn handler(_: c_int) {
        super::DONE.store(true, Ordering::Relaxed);
    }

    #[cfg(feature = "termination")]
    #[inline]
    pub unsafe fn set_os_handler(handler: fn(c_int)) {
        signal(SIGINT, ::std::mem::transmute::<_, sighandler_t>(handler));
        signal(SIGTERM, ::std::mem::transmute::<_, sighandler_t>(handler));
    }

    #[cfg(not(feature = "termination"))]
    #[inline]
    pub unsafe fn set_os_handler(handler: fn(c_int)) {
        signal(SIGINT, ::std::mem::transmute::<_, sighandler_t>(handler));
    }
}
#[cfg(windows)]
mod platform {
    extern crate winapi;
    extern crate kernel32;
    use self::kernel32::SetConsoleCtrlHandler;
    use self::winapi::{BOOL, DWORD, TRUE};
    use std::sync::atomic::Ordering;

    pub unsafe extern "system" fn handler(_: DWORD) -> BOOL {
        super::DONE.store(true, Ordering::Relaxed);
        TRUE
    }
    #[inline]
    pub unsafe fn set_os_handler(handler: unsafe extern "system" fn(DWORD) -> BOOL) {
        SetConsoleCtrlHandler(Some(handler), TRUE);
    }
}
use self::platform::*;

/// Sets up the signal handler for Ctrl-C using default polling rate of 100ms.
/// # Example
/// ```
/// ctrlc::set_handler(|| println!("Hello world!"));
/// ```
pub fn set_handler<F>(user_handler: F)
    where F: Fn() -> () + 'static + Send
{
    self::set_handler_with_polling_rate(user_handler, time::Duration::from_millis(100));
}

/// Sets up the signal handler for Ctrl-C using a custom polling rate.
/// The polling rate is the amount of time the internal spinloop of CtrlC sleeps between
/// iterations. Because condition variables are not safe to use inside a signal handler,
/// CtrlC (from version 1.1.0) uses a spinloop and an atomic boolean instead.
///
/// Normally you should use `set_handler` instead, but if the default rate of  100 milliseconds
/// is too fast or too slow for you, you can use this routine instead to set your own.
/// # Example
/// ```
/// # use std::time::Duration;
/// ctrlc::set_handler_with_polling_rate(
///     || println!("Hello world!"),
///     Duration::from_millis(10)
/// );
/// ```
pub fn set_handler_with_polling_rate<F>(user_handler: F, polling_rate: time::Duration)
    where F: Fn() -> () + 'static + Send
{
    unsafe {
        set_os_handler(handler);
    }
    thread::spawn(move || {
        loop {
            if DONE.compare_and_swap(true, false, Ordering::Relaxed) {
                user_handler();
            }
            thread::sleep(polling_rate);
        }
    });
}