ctrlc-3.4.2/.cargo_vcs_info.json0000644000000001360000000000100121510ustar { "git": { "sha1": "4e5f374bdba3d35c10906f10d460755fdec6324b" }, "path_in_vcs": "" }ctrlc-3.4.2/.gitignore000064400000000000000000000000221046102023000127230ustar 00000000000000target Cargo.lock ctrlc-3.4.2/Cargo.lock0000644000000067430000000000100101360ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "bitflags" version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "ctrlc" version = "3.4.2" dependencies = [ "nix", "signal-hook", "windows-sys", ] [[package]] name = "libc" version = "0.2.147" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3" [[package]] name = "nix" version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2eb04e9c688eff1c89d72b407f168cf79bb9e867a9d3323ed6c01519eb9cc053" dependencies = [ "bitflags", "cfg-if", "libc", ] [[package]] name = "signal-hook" version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8621587d4798caf8eb44879d42e56b9a93ea5dcd315a6487c357130095b62801" dependencies = [ "libc", "signal-hook-registry", ] [[package]] name = "signal-hook-registry" version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" dependencies = [ "libc", ] [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a18201040b24831fbb9e4eb208f8892e1f50a37feb53cc7ff887feb8f50e7cd" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea" [[package]] name = "windows_aarch64_msvc" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef" [[package]] name = "windows_i686_gnu" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313" [[package]] name = "windows_i686_msvc" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a" [[package]] name = "windows_x86_64_gnu" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d6fa32db2bc4a2f5abeacf2b69f7992cd09dca97498da74a151a3132c26befd" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e" [[package]] name = "windows_x86_64_msvc" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" ctrlc-3.4.2/Cargo.toml0000644000000033440000000000100101530ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" rust-version = "1.63.0" name = "ctrlc" version = "3.4.2" authors = ["Antti Keränen "] exclude = [ "/.travis.yml", "/appveyor.yml", ] description = "Easy Ctrl-C handler for Rust projects" homepage = "https://github.com/Detegr/rust-ctrlc" documentation = "https://detegr.github.io/doc/ctrlc" readme = "README.md" keywords = [ "ctrlc", "signal", "SIGINT", ] categories = ["os"] license = "MIT/Apache-2.0" repository = "https://github.com/Detegr/rust-ctrlc.git" [[test]] name = "main" path = "tests/main/mod.rs" harness = false [[test]] name = "issue_97" path = "tests/main/issue_97.rs" harness = false [dev-dependencies.signal-hook] version = "0.3" [features] termination = [] [target."cfg(unix)".dependencies.nix] version = "0.27" features = [ "fs", "signal", ] default-features = false [target."cfg(windows)".dependencies.windows-sys] version = "0.52" features = [ "Win32_Foundation", "Win32_System_Threading", "Win32_Security", "Win32_System_Console", ] [target."cfg(windows)".dev-dependencies.windows-sys] version = "0.52" features = [ "Win32_Storage_FileSystem", "Win32_Foundation", "Win32_System_IO", "Win32_System_Console", ] [badges.maintenance] status = "passively-maintained" ctrlc-3.4.2/Cargo.toml.orig000064400000000000000000000023311046102023000136270ustar 00000000000000[package] name = "ctrlc" version = "3.4.2" authors = ["Antti Keränen "] description = "Easy Ctrl-C handler for Rust projects" documentation = "https://detegr.github.io/doc/ctrlc" homepage = "https://github.com/Detegr/rust-ctrlc" keywords = ["ctrlc", "signal", "SIGINT"] categories = ["os"] license = "MIT/Apache-2.0" repository = "https://github.com/Detegr/rust-ctrlc.git" exclude = ["/.travis.yml", "/appveyor.yml"] edition = "2018" readme = "README.md" rust-version = "1.63.0" [target.'cfg(unix)'.dependencies] nix = { version = "0.27", default-features = false, features = ["fs", "signal"]} [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.52", features = ["Win32_Foundation", "Win32_System_Threading", "Win32_Security", "Win32_System_Console"] } [target.'cfg(windows)'.dev-dependencies] windows-sys = { version = "0.52", features = ["Win32_Storage_FileSystem", "Win32_Foundation", "Win32_System_IO", "Win32_System_Console"] } [features] termination = [] [[test]] harness = false name = "main" path = "tests/main/mod.rs" [[test]] harness = false name = "issue_97" path = "tests/main/issue_97.rs" [dev-dependencies] signal-hook = "0.3" [badges] maintenance = { status = "passively-maintained" } ctrlc-3.4.2/LICENSE-APACHE000064400000000000000000000251241046102023000126710ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2017 CtrlC developers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ctrlc-3.4.2/LICENSE-MIT000064400000000000000000000017771046102023000124110ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ctrlc-3.4.2/README.md000064400000000000000000000034261046102023000122250ustar 00000000000000# CtrlC [![Build Status](https://travis-ci.org/Detegr/rust-ctrlc.svg?branch=master)](https://travis-ci.org/Detegr/rust-ctrlc) [![Build status](https://ci.appveyor.com/api/projects/status/kwg1uu2w2aqn9ta9/branch/master?svg=true)](https://ci.appveyor.com/project/Detegr/rust-ctrlc/branch/master) A simple easy to use wrapper around Ctrl-C signal. [Documentation](http://detegr.github.io/doc/ctrlc/) ## Example usage In `cargo.toml`: ```toml [dependencies] ctrlc = "3.4" ``` then, in `main.rs` ```rust use std::sync::mpsc::channel; use ctrlc; fn main() { let (tx, rx) = channel(); ctrlc::set_handler(move || tx.send(()).expect("Could not send signal on channel.")) .expect("Error setting Ctrl-C handler"); println!("Waiting for Ctrl-C..."); rx.recv().expect("Could not receive from channel."); println!("Got it! Exiting..."); } ``` #### Try the example yourself `cargo build --examples && target/debug/examples/readme_example` ## Handling SIGTERM and SIGHUP Add CtrlC to Cargo.toml using `termination` feature and CtrlC will handle SIGINT, SIGTERM and SIGHUP. ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be dual licensed as above, without any additional terms or conditions. ## Similar crates There are alternatives that give you more control over the different signals and/or add async support. - [signal-hook](https://github.com/vorner/signal-hook) - [tokio::signal](https://docs.rs/tokio/latest/tokio/signal/index.html) ctrlc-3.4.2/examples/issue_46_example.rs000064400000000000000000000012151046102023000163000ustar 00000000000000use std::process; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::thread; use std::time::Duration; fn main() { let running = Arc::new(AtomicUsize::new(0)); let r = running.clone(); ctrlc::set_handler(move || { let prev = r.fetch_add(1, Ordering::SeqCst); if prev == 0 { println!("Exiting..."); } else { process::exit(0); } }) .expect("Error setting Ctrl-C handler"); println!("Running..."); for _ in 1..6 { thread::sleep(Duration::from_secs(5)); if running.load(Ordering::SeqCst) > 0 { break; } } } ctrlc-3.4.2/examples/readme_example.rs000064400000000000000000000013431046102023000160760ustar 00000000000000// Copyright (c) 2015 CtrlC developers // Licensed under the Apache License, Version 2.0 // or the MIT // license , // at your option. All files in the project carrying such // notice may not be copied, modified, or distributed except // according to those terms. use ctrlc; use std::sync::mpsc::channel; fn main() { let (tx, rx) = channel(); ctrlc::set_handler(move || tx.send(()).expect("Could not send signal on channel.")) .expect("Error setting Ctrl-C handler"); println!("Waiting for Ctrl-C..."); rx.recv().expect("Could not receive from channel."); println!("Got it! Exiting..."); } ctrlc-3.4.2/src/error.rs000064400000000000000000000025361046102023000132350ustar 00000000000000use crate::platform; use std::fmt; /// Ctrl-C error. #[derive(Debug)] pub enum Error { /// Signal could not be found from the system. NoSuchSignal(crate::SignalType), /// Ctrl-C signal handler already registered. MultipleHandlers, /// Unexpected system error. System(std::io::Error), } impl Error { fn describe(&self) -> &str { match *self { Error::NoSuchSignal(_) => "Signal could not be found from the system", Error::MultipleHandlers => "Ctrl-C signal handler already registered", Error::System(_) => "Unexpected system error", } } } impl From for Error { fn from(e: platform::Error) -> Error { #[cfg(not(windows))] if e == platform::Error::EEXIST { return Error::MultipleHandlers; } let system_error = std::io::Error::new(std::io::ErrorKind::Other, e); Error::System(system_error) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Ctrl-C error: {}", self.describe()) } } impl std::error::Error for Error { fn description(&self) -> &str { self.describe() } fn cause(&self) -> Option<&dyn std::error::Error> { match *self { Error::System(ref e) => Some(e), _ => None, } } } ctrlc-3.4.2/src/lib.rs000064400000000000000000000115721046102023000126520ustar 00000000000000// Copyright (c) 2017 CtrlC developers // Licensed under the Apache License, Version 2.0 // or the MIT // license , // at your option. All files in the project carrying such // notice may not be copied, modified, or distributed except // according to those terms. #![warn(missing_docs)] //! Cross platform handling of Ctrl-C signals. //! //! [HandlerRoutine]:https://msdn.microsoft.com/en-us/library/windows/desktop/ms683242.aspx //! //! [set_handler()](fn.set_handler.html) allows setting a handler closure which is executed on //! `Ctrl+C`. On Unix, this corresponds to a `SIGINT` signal. On windows, `Ctrl+C` corresponds to //! [`CTRL_C_EVENT`][HandlerRoutine] or [`CTRL_BREAK_EVENT`][HandlerRoutine]. //! //! Setting a handler will start a new dedicated signal handling thread where we //! execute the handler each time we receive a `Ctrl+C` signal. There can only be //! one handler, you would typically set one at the start of your program. //! //! # Example //! ```no_run //! # #[allow(clippy::needless_doctest_main)] //! 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); //! }).expect("Error setting Ctrl-C handler"); //! //! println!("Waiting for Ctrl-C..."); //! while running.load(Ordering::SeqCst) {} //! println!("Got it! Exiting..."); //! } //! ``` //! //! # Handling SIGTERM and SIGHUP //! Handling of `SIGTERM and SIGHUP` can be enabled with `termination` feature. If this is enabled, //! the handler specified by `set_handler()` will be executed for `SIGINT`, `SIGTERM` and `SIGHUP`. //! #[macro_use] mod error; mod platform; pub use platform::Signal; mod signal; pub use signal::*; pub use error::Error; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Mutex; use std::thread; static INIT: AtomicBool = AtomicBool::new(false); static INIT_LOCK: Mutex<()> = Mutex::new(()); /// Register signal handler for Ctrl-C. /// /// Starts a new dedicated signal handling thread. Should only be called once, /// typically at the start of your program. /// /// # Example /// ```no_run /// ctrlc::set_handler(|| println!("Hello world!")).expect("Error setting Ctrl-C handler"); /// ``` /// /// # Warning /// On Unix, the handler registration for `SIGINT`, (`SIGTERM` and `SIGHUP` if termination feature /// is enabled) or `SA_SIGINFO` posix signal handlers will be overwritten. On Windows, multiple /// handler routines are allowed, but they are called on a last-registered, first-called basis /// until the signal is handled. /// /// ctrlc::try_set_handler will error (on Unix) if another signal handler exists for the same /// signal(s) that ctrlc is trying to attach the handler to. /// /// On Unix, signal dispositions and signal handlers are inherited by child processes created via /// `fork(2)` on, but not by child processes created via `execve(2)`. /// Signal handlers are not inherited on Windows. /// /// # Errors /// Will return an error if a system error occurred while setting the handler. /// /// # Panics /// Any panic in the handler will not be caught and will cause the signal handler thread to stop. pub fn set_handler(user_handler: F) -> Result<(), Error> where F: FnMut() + 'static + Send, { init_and_set_handler(user_handler, true) } /// The same as ctrlc::set_handler but errors if a handler already exists for the signal(s). /// /// # Errors /// Will return an error if another handler exists or if a system error occurred while setting the /// handler. pub fn try_set_handler(user_handler: F) -> Result<(), Error> where F: FnMut() + 'static + Send, { init_and_set_handler(user_handler, false) } fn init_and_set_handler(user_handler: F, overwrite: bool) -> Result<(), Error> where F: FnMut() + 'static + Send, { if !INIT.load(Ordering::Acquire) { let _guard = INIT_LOCK.lock().unwrap(); if !INIT.load(Ordering::Relaxed) { set_handler_inner(user_handler, overwrite)?; INIT.store(true, Ordering::Release); return Ok(()); } } Err(Error::MultipleHandlers) } fn set_handler_inner(mut user_handler: F, overwrite: bool) -> Result<(), Error> where F: FnMut() + 'static + Send, { unsafe { match platform::init_os_handler(overwrite) { Ok(_) => {} Err(err) => { return Err(err.into()); } } } thread::Builder::new() .name("ctrl-c".into()) .spawn(move || loop { unsafe { platform::block_ctrl_c().expect("Critical system error while waiting for Ctrl-C"); } user_handler(); }) .expect("failed to spawn thread"); Ok(()) } ctrlc-3.4.2/src/platform/mod.rs000064400000000000000000000010031046102023000144730ustar 00000000000000// Copyright (c) 2017 CtrlC developers // Licensed under the Apache License, Version 2.0 // or the MIT // license , // at your option. All files in the project carrying such // notice may not be copied, modified, or distributed except // according to those terms. #[cfg(unix)] mod unix; #[cfg(windows)] mod windows; #[cfg(unix)] pub use self::unix::*; #[cfg(windows)] pub use self::windows::*; ctrlc-3.4.2/src/platform/unix/mod.rs000064400000000000000000000135751046102023000154770ustar 00000000000000// Copyright (c) 2017 CtrlC developers // Licensed under the Apache License, Version 2.0 // or the MIT // license , // at your option. All files in the project carrying such // notice may not be copied, modified, or distributed except // according to those terms. use crate::error::Error as CtrlcError; use nix::unistd; use std::os::unix::io::RawFd; static mut PIPE: (RawFd, RawFd) = (-1, -1); /// Platform specific error type pub type Error = nix::Error; /// Platform specific signal type pub type Signal = nix::sys::signal::Signal; extern "C" fn os_handler(_: nix::libc::c_int) { // Assuming this always succeeds. Can't really handle errors in any meaningful way. unsafe { let _ = unistd::write(PIPE.1, &[0u8]); } } // pipe2(2) is not available on macOS, iOS, AIX or Haiku, so we need to use pipe(2) and fcntl(2) #[inline] #[cfg(any( target_os = "ios", target_os = "macos", target_os = "haiku", target_os = "aix", target_os = "nto", ))] fn pipe2(flags: nix::fcntl::OFlag) -> nix::Result<(RawFd, RawFd)> { use nix::fcntl::{fcntl, FcntlArg, FdFlag, OFlag}; let pipe = unistd::pipe()?; let mut res = Ok(0); if flags.contains(OFlag::O_CLOEXEC) { res = res .and_then(|_| fcntl(pipe.0, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC))) .and_then(|_| fcntl(pipe.1, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC))); } if flags.contains(OFlag::O_NONBLOCK) { res = res .and_then(|_| fcntl(pipe.0, FcntlArg::F_SETFL(OFlag::O_NONBLOCK))) .and_then(|_| fcntl(pipe.1, FcntlArg::F_SETFL(OFlag::O_NONBLOCK))); } match res { Ok(_) => Ok(pipe), Err(e) => { let _ = unistd::close(pipe.0); let _ = unistd::close(pipe.1); Err(e) } } } #[inline] #[cfg(not(any( target_os = "ios", target_os = "macos", target_os = "haiku", target_os = "aix", target_os = "nto", )))] fn pipe2(flags: nix::fcntl::OFlag) -> nix::Result<(RawFd, RawFd)> { unistd::pipe2(flags) } /// Register os signal handler. /// /// Must be called before calling [`block_ctrl_c()`](fn.block_ctrl_c.html) /// and should only be called once. /// /// # Errors /// Will return an error if a system error occurred. /// #[inline] pub unsafe fn init_os_handler(overwrite: bool) -> Result<(), Error> { use nix::fcntl; use nix::sys::signal; PIPE = pipe2(fcntl::OFlag::O_CLOEXEC)?; let close_pipe = |e: nix::Error| -> Error { // Try to close the pipes. close() should not fail, // but if it does, there isn't much we can do let _ = unistd::close(PIPE.1); let _ = unistd::close(PIPE.0); e }; // Make sure we never block on write in the os handler. if let Err(e) = fcntl::fcntl(PIPE.1, fcntl::FcntlArg::F_SETFL(fcntl::OFlag::O_NONBLOCK)) { return Err(close_pipe(e)); } let handler = signal::SigHandler::Handler(os_handler); #[cfg(not(target_os = "nto"))] let new_action = signal::SigAction::new( handler, signal::SaFlags::SA_RESTART, signal::SigSet::empty(), ); // SA_RESTART is not supported on QNX Neutrino 7.1 and before #[cfg(target_os = "nto")] let new_action = signal::SigAction::new(handler, signal::SaFlags::empty(), signal::SigSet::empty()); let sigint_old = match signal::sigaction(signal::Signal::SIGINT, &new_action) { Ok(old) => old, Err(e) => return Err(close_pipe(e)), }; if !overwrite && sigint_old.handler() != signal::SigHandler::SigDfl { signal::sigaction(signal::Signal::SIGINT, &sigint_old).unwrap(); return Err(close_pipe(nix::Error::EEXIST)); } #[cfg(feature = "termination")] { let sigterm_old = match signal::sigaction(signal::Signal::SIGTERM, &new_action) { Ok(old) => old, Err(e) => { signal::sigaction(signal::Signal::SIGINT, &sigint_old).unwrap(); return Err(close_pipe(e)); } }; if !overwrite && sigterm_old.handler() != signal::SigHandler::SigDfl { signal::sigaction(signal::Signal::SIGINT, &sigint_old).unwrap(); signal::sigaction(signal::Signal::SIGTERM, &sigterm_old).unwrap(); return Err(close_pipe(nix::Error::EEXIST)); } let sighup_old = match signal::sigaction(signal::Signal::SIGHUP, &new_action) { Ok(old) => old, Err(e) => { signal::sigaction(signal::Signal::SIGINT, &sigint_old).unwrap(); signal::sigaction(signal::Signal::SIGTERM, &sigterm_old).unwrap(); return Err(close_pipe(e)); } }; if !overwrite && sighup_old.handler() != signal::SigHandler::SigDfl { signal::sigaction(signal::Signal::SIGINT, &sigint_old).unwrap(); signal::sigaction(signal::Signal::SIGTERM, &sigterm_old).unwrap(); signal::sigaction(signal::Signal::SIGHUP, &sighup_old).unwrap(); return Err(close_pipe(nix::Error::EEXIST)); } } Ok(()) } /// Blocks until a Ctrl-C signal is received. /// /// Must be called after calling [`init_os_handler()`](fn.init_os_handler.html). /// /// # Errors /// Will return an error if a system error occurred. /// #[inline] pub unsafe fn block_ctrl_c() -> Result<(), CtrlcError> { use std::io; let mut buf = [0u8]; // TODO: Can we safely convert the pipe fd into a std::io::Read // with std::os::unix::io::FromRawFd, this would handle EINTR // and everything for us. loop { match unistd::read(PIPE.0, &mut buf[..]) { Ok(1) => break, Ok(_) => return Err(CtrlcError::System(io::ErrorKind::UnexpectedEof.into())), Err(nix::errno::Errno::EINTR) => {} Err(e) => return Err(e.into()), } } Ok(()) } ctrlc-3.4.2/src/platform/windows/mod.rs000064400000000000000000000046151046102023000162010ustar 00000000000000// Copyright (c) 2017 CtrlC developers // Licensed under the Apache License, Version 2.0 // or the MIT // license , // at your option. All files in the project carrying such // notice may not be copied, modified, or distributed except // according to those terms. use std::io; use std::ptr; use windows_sys::Win32::Foundation::{CloseHandle, BOOL, HANDLE, WAIT_FAILED, WAIT_OBJECT_0}; use windows_sys::Win32::System::Console::SetConsoleCtrlHandler; use windows_sys::Win32::System::Threading::{ CreateSemaphoreA, ReleaseSemaphore, WaitForSingleObject, INFINITE, }; /// Platform specific error type pub type Error = io::Error; /// Platform specific signal type pub type Signal = u32; const MAX_SEM_COUNT: i32 = 255; static mut SEMAPHORE: HANDLE = 0 as HANDLE; const TRUE: BOOL = 1; const FALSE: BOOL = 0; unsafe extern "system" fn os_handler(_: u32) -> BOOL { // Assuming this always succeeds. Can't really handle errors in any meaningful way. ReleaseSemaphore(SEMAPHORE, 1, ptr::null_mut()); TRUE } /// Register os signal handler. /// /// Must be called before calling [`block_ctrl_c()`](fn.block_ctrl_c.html) /// and should only be called once. /// /// # Errors /// Will return an error if a system error occurred. /// #[inline] pub unsafe fn init_os_handler(_overwrite: bool) -> Result<(), Error> { SEMAPHORE = CreateSemaphoreA(ptr::null_mut(), 0, MAX_SEM_COUNT, ptr::null()); if SEMAPHORE == 0 { return Err(io::Error::last_os_error()); } if SetConsoleCtrlHandler(Some(os_handler), TRUE) == FALSE { let e = io::Error::last_os_error(); CloseHandle(SEMAPHORE); SEMAPHORE = 0 as HANDLE; return Err(e); } Ok(()) } /// Blocks until a Ctrl-C signal is received. /// /// Must be called after calling [`init_os_handler()`](fn.init_os_handler.html). /// /// # Errors /// Will return an error if a system error occurred. /// #[inline] pub unsafe fn block_ctrl_c() -> Result<(), Error> { match WaitForSingleObject(SEMAPHORE, INFINITE) { WAIT_OBJECT_0 => Ok(()), WAIT_FAILED => Err(io::Error::last_os_error()), ret => Err(io::Error::new( io::ErrorKind::Other, format!( "WaitForSingleObject(), unexpected return value \"{:x}\"", ret ), )), } } ctrlc-3.4.2/src/signal.rs000064400000000000000000000014601046102023000133540ustar 00000000000000// Copyright (c) 2017 CtrlC developers // Licensed under the Apache License, Version 2.0 // or the MIT // license , // at your option. All files in the project carrying such // notice may not be copied, modified, or distributed except // according to those terms. use crate::platform; /// A cross-platform way to represent Ctrl-C or program termination signal. Other /// signals/events are supported via `Other`-variant. #[derive(Debug)] pub enum SignalType { /// Ctrl-C Ctrlc, /// Program termination /// Maps to `SIGTERM` and `SIGHUP` on *nix, `CTRL_CLOSE_EVENT` on Windows. Termination, /// Other signal/event using platform-specific data Other(platform::Signal), } ctrlc-3.4.2/tests/main/harness.rs000064400000000000000000000161061046102023000150440ustar 00000000000000// Copyright (c) 2023 CtrlC developers // Licensed under the Apache License, Version 2.0 // or the MIT // license , // at your option. All files in the project carrying such // notice may not be copied, modified, or distributed except // according to those terms. #[cfg(unix)] pub mod platform { use std::io; pub unsafe fn setup() -> io::Result<()> { Ok(()) } pub unsafe fn cleanup() -> io::Result<()> { Ok(()) } pub unsafe fn raise_ctrl_c() { nix::sys::signal::raise(nix::sys::signal::SIGINT).unwrap(); } pub unsafe fn print(fmt: ::std::fmt::Arguments) { use self::io::Write; let stdout = ::std::io::stdout(); stdout.lock().write_fmt(fmt).unwrap(); } } #[cfg(windows)] pub mod platform { use std::io; use std::ptr; use windows_sys::Win32::Foundation::{ GENERIC_READ, GENERIC_WRITE, HANDLE, INVALID_HANDLE_VALUE, }; use windows_sys::Win32::Storage::FileSystem::{ CreateFileA, WriteFile, FILE_SHARE_WRITE, OPEN_EXISTING, }; use windows_sys::Win32::System::Console::{ AllocConsole, AttachConsole, FreeConsole, GenerateConsoleCtrlEvent, GetConsoleMode, GetStdHandle, SetStdHandle, ATTACH_PARENT_PROCESS, CTRL_C_EVENT, STD_ERROR_HANDLE, STD_OUTPUT_HANDLE, }; /// Stores a piped stdout handle or a cache that gets /// flushed when we reattached to the old console. enum Output { Pipe(HANDLE), Cached(Vec), } static mut OLD_OUT: *mut Output = 0 as *mut Output; impl io::Write for Output { fn write(&mut self, buf: &[u8]) -> io::Result { match *self { Output::Pipe(handle) => unsafe { let mut n = 0u32; if WriteFile( handle, buf.as_ptr(), buf.len() as u32, &mut n as *mut u32, ptr::null_mut(), ) == 0 { Err(io::Error::last_os_error()) } else { Ok(n as usize) } }, Output::Cached(ref mut s) => s.write(buf), } } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl Output { /// Stores current piped stdout or creates a new output cache that will /// be written to stdout at a later time. fn new() -> io::Result { unsafe { let stdout = GetStdHandle(STD_OUTPUT_HANDLE); if stdout == 0 || stdout == INVALID_HANDLE_VALUE { return Err(io::Error::last_os_error()); } let mut out = 0u32; match GetConsoleMode(stdout, &mut out as *mut u32) { 0 => Ok(Output::Pipe(stdout)), _ => Ok(Output::Cached(Vec::new())), } } } /// Set stdout/stderr and flush cache. unsafe fn set_as_std(self) -> io::Result<()> { let stdout = match self { Output::Pipe(h) => h, Output::Cached(_) => get_stdout()?, }; if SetStdHandle(STD_OUTPUT_HANDLE, stdout) == 0 { return Err(io::Error::last_os_error()); } if SetStdHandle(STD_ERROR_HANDLE, stdout) == 0 { return Err(io::Error::last_os_error()); } match self { Output::Pipe(_) => Ok(()), Output::Cached(ref s) => { // Write cached output use self::io::Write; let out = io::stdout(); out.lock().write_all(&s[..])?; Ok(()) } } } } unsafe fn get_stdout() -> io::Result { let stdout = CreateFileA( "CONOUT$\0".as_ptr(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, ptr::null_mut(), OPEN_EXISTING, 0, 0 as HANDLE, ); if stdout == 0 || stdout == INVALID_HANDLE_VALUE { Err(io::Error::last_os_error()) } else { Ok(stdout) } } /// Detach from the current console and create a new one, /// We do this because GenerateConsoleCtrlEvent() sends ctrl-c events /// to all processes on the same console. We want events to be received /// only by our process. /// /// This breaks rust's stdout pre 1.18.0. Rust used to /// [cache the std handles](https://github.com/rust-lang/rust/pull/40516) /// pub unsafe fn setup() -> io::Result<()> { let old_out = Output::new()?; if FreeConsole() == 0 { return Err(io::Error::last_os_error()); } if AllocConsole() == 0 { return Err(io::Error::last_os_error()); } // AllocConsole will not always set stdout/stderr to the to the console buffer // of the new terminal. let stdout = get_stdout()?; if SetStdHandle(STD_OUTPUT_HANDLE, stdout) == 0 { return Err(io::Error::last_os_error()); } if SetStdHandle(STD_ERROR_HANDLE, stdout) == 0 { return Err(io::Error::last_os_error()); } OLD_OUT = Box::into_raw(Box::new(old_out)); Ok(()) } /// Reattach to the old console. pub unsafe fn cleanup() -> io::Result<()> { if FreeConsole() == 0 { return Err(io::Error::last_os_error()); } if AttachConsole(ATTACH_PARENT_PROCESS) == 0 { return Err(io::Error::last_os_error()); } Box::from_raw(OLD_OUT).set_as_std()?; Ok(()) } /// This will signal the whole process group. pub unsafe fn raise_ctrl_c() { assert!(GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0) != 0); } /// Print to both consoles, this is not thread safe. pub unsafe fn print(fmt: ::std::fmt::Arguments) { use self::io::Write; { let stdout = io::stdout(); stdout.lock().write_fmt(fmt).unwrap(); } { assert!(!OLD_OUT.is_null()); (*OLD_OUT).write_fmt(fmt).unwrap(); } } } macro_rules! run_tests { ( $($test_fn:ident),* ) => { unsafe { $( harness::platform::print(format_args!("test {} ... ", stringify!($test_fn))); $test_fn(); harness::platform::print(format_args!("ok\n")); )* } } } pub fn run_harness(f: fn()) { unsafe { platform::setup().unwrap(); } let default = std::panic::take_hook(); std::panic::set_hook(Box::new(move |info| { unsafe { platform::cleanup().unwrap(); } (default)(info); })); println!(""); f(); println!(""); unsafe { platform::cleanup().unwrap(); } } ctrlc-3.4.2/tests/main/issue_97.rs000064400000000000000000000015251046102023000150470ustar 00000000000000// Copyright (c) 2023 CtrlC developers // Licensed under the Apache License, Version 2.0 // or the MIT // license , // at your option. All files in the project carrying such // notice may not be copied, modified, or distributed except // according to those terms. #[macro_use] mod harness; use harness::{platform, run_harness}; mod test_signal_hook; use test_signal_hook::run_signal_hook; fn expect_multiple_handlers() { #[cfg(not(windows))] match ctrlc::try_set_handler(|| {}) { Err(ctrlc::Error::MultipleHandlers) => {} _ => panic!("Expected Error::MultipleHandlers"), } } fn tests() { run_tests!(run_signal_hook); run_tests!(expect_multiple_handlers); } fn main() { run_harness(tests); } ctrlc-3.4.2/tests/main/mod.rs000064400000000000000000000021351046102023000141550ustar 00000000000000// Copyright (c) 2023 CtrlC developers // Licensed under the Apache License, Version 2.0 // or the MIT // license , // at your option. All files in the project carrying such // notice may not be copied, modified, or distributed except // according to those terms. #[macro_use] mod harness; use harness::{platform, run_harness}; use std::sync::{ atomic::{AtomicBool, Ordering}, Arc, }; fn test_set_handler() { let flag = Arc::new(AtomicBool::new(false)); let flag_handler = Arc::clone(&flag); ctrlc::set_handler(move || { flag_handler.store(true, Ordering::SeqCst); }) .unwrap(); unsafe { platform::raise_ctrl_c(); } std::thread::sleep(std::time::Duration::from_millis(100)); assert!(flag.load(Ordering::SeqCst)); match ctrlc::set_handler(|| {}) { Err(ctrlc::Error::MultipleHandlers) => {} ret => panic!("{:?}", ret), } } fn tests() { run_tests!(test_set_handler); } fn main() { run_harness(tests); } ctrlc-3.4.2/tests/main/test_signal_hook.rs000064400000000000000000000014201046102023000167260ustar 00000000000000// Copyright (c) 2023 CtrlC developers // Licensed under the Apache License, Version 2.0 // or the MIT // license , // at your option. All files in the project carrying such // notice may not be copied, modified, or distributed except // according to those terms. use std::sync::{ atomic::{AtomicBool, Ordering}, Arc, }; pub fn run_signal_hook() { let hook = Arc::new(AtomicBool::new(false)); signal_hook::flag::register(signal_hook::consts::SIGINT, Arc::clone(&hook)).unwrap(); unsafe { super::platform::raise_ctrl_c(); } std::thread::sleep(std::time::Duration::from_millis(100)); assert!(hook.load(Ordering::SeqCst)); }