| 1 |
// Copyright (c) 2017 CtrlC developers |
| 2 |
// Licensed under the Apache License, Version 2.0 |
| 3 |
// <LICENSE-APACHE or |
| 4 |
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT |
| 5 |
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, |
| 6 |
// at your option. All files in the project carrying such |
| 7 |
// notice may not be copied, modified, or distributed except |
| 8 |
// according to those terms. |
| 9 |
|
| 10 |
use std::io; |
| 11 |
use std::ptr; |
| 12 |
use windows_sys::core::BOOL; |
| 13 |
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, WAIT_FAILED, WAIT_OBJECT_0}; |
| 14 |
use windows_sys::Win32::System::Console::SetConsoleCtrlHandler; |
| 15 |
use windows_sys::Win32::System::Threading::{ |
| 16 |
CreateSemaphoreA, ReleaseSemaphore, WaitForSingleObject, INFINITE, |
| 17 |
}; |
| 18 |
|
| 19 |
/// Platform specific error type |
| 20 |
pub type Error = io::Error; |
| 21 |
|
| 22 |
/// Platform specific signal type |
| 23 |
pub type Signal = u32; |
| 24 |
|
| 25 |
const MAX_SEM_COUNT: i32 = 255; |
| 26 |
static mut SEMAPHORE: HANDLE = 0 as HANDLE; |
| 27 |
const TRUE: BOOL = 1; |
| 28 |
const FALSE: BOOL = 0; |
| 29 |
|
| 30 |
unsafe extern "system" fn os_handler(_: u32) -> BOOL { |
| 31 |
// Assuming this always succeeds. Can't really handle errors in any meaningful way. |
| 32 |
ReleaseSemaphore(SEMAPHORE, 1, ptr::null_mut()); |
| 33 |
TRUE |
| 34 |
} |
| 35 |
|
| 36 |
/// Register os signal handler. |
| 37 |
/// |
| 38 |
/// Must be called before calling [`block_ctrl_c()`](fn.block_ctrl_c.html) |
| 39 |
/// and should only be called once. |
| 40 |
/// |
| 41 |
/// # Errors |
| 42 |
/// Will return an error if a system error occurred. |
| 43 |
/// |
| 44 |
#[inline] |
| 45 |
pub unsafe fn init_os_handler(_overwrite: bool) -> Result<(), Error> { |
| 46 |
SEMAPHORE = CreateSemaphoreA(ptr::null_mut(), 0, MAX_SEM_COUNT, ptr::null()); |
| 47 |
if SEMAPHORE.is_null() { |
| 48 |
return Err(io::Error::last_os_error()); |
| 49 |
} |
| 50 |
|
| 51 |
if SetConsoleCtrlHandler(Some(os_handler), TRUE) == FALSE { |
| 52 |
let e = io::Error::last_os_error(); |
| 53 |
CloseHandle(SEMAPHORE); |
| 54 |
SEMAPHORE = 0 as HANDLE; |
| 55 |
return Err(e); |
| 56 |
} |
| 57 |
|
| 58 |
Ok(()) |
| 59 |
} |
| 60 |
|
| 61 |
/// Blocks until a Ctrl-C signal is received. |
| 62 |
/// |
| 63 |
/// Must be called after calling [`init_os_handler()`](fn.init_os_handler.html). |
| 64 |
/// |
| 65 |
/// # Errors |
| 66 |
/// Will return an error if a system error occurred. |
| 67 |
/// |
| 68 |
#[inline] |
| 69 |
pub unsafe fn block_ctrl_c() -> Result<(), Error> { |
| 70 |
match WaitForSingleObject(SEMAPHORE, INFINITE) { |
| 71 |
WAIT_OBJECT_0 => Ok(()), |
| 72 |
WAIT_FAILED => Err(io::Error::last_os_error()), |
| 73 |
ret => Err(io::Error::new( |
| 74 |
io::ErrorKind::Other, |
| 75 |
format!( |
| 76 |
"WaitForSingleObject(), unexpected return value \"{:x}\"", |
| 77 |
ret |
| 78 |
), |
| 79 |
)), |
| 80 |
} |
| 81 |
} |