diff options
author | Michal 'vorner' Vaner <vorner@vorner.cz> | 2018-09-01 10:57:20 +0200 |
---|---|---|
committer | Michal 'vorner' Vaner <vorner@vorner.cz> | 2018-09-14 23:25:57 +0200 |
commit | 35687f1d187ec21019906f900e99f064bf55c0eb (patch) | |
tree | dc8d638ecc521655d5e05f8157bf74aa8a65bf33 /tokio-signal | |
parent | e7dc3a10916f298915ae40503b33041e53593c86 (diff) |
signal: Move to tokio-signal subdirectory
As a preparation to merge with tokio.
Diffstat (limited to 'tokio-signal')
-rw-r--r-- | tokio-signal/.travis.yml | 29 | ||||
-rw-r--r-- | tokio-signal/CHANGELOG.md | 41 | ||||
-rw-r--r-- | tokio-signal/Cargo.toml | 36 | ||||
-rw-r--r-- | tokio-signal/LICENSE-APACHE | 201 | ||||
-rw-r--r-- | tokio-signal/LICENSE-MIT | 25 | ||||
-rw-r--r-- | tokio-signal/README.md | 58 | ||||
-rw-r--r-- | tokio-signal/appveyor.yml | 35 | ||||
-rw-r--r-- | tokio-signal/examples/ctrl-c.rs | 63 | ||||
-rw-r--r-- | tokio-signal/examples/multiple.rs | 38 | ||||
-rw-r--r-- | tokio-signal/examples/sighup-example.rs | 39 | ||||
-rw-r--r-- | tokio-signal/src/lib.rs | 147 | ||||
-rw-r--r-- | tokio-signal/src/unix.rs | 385 | ||||
-rw-r--r-- | tokio-signal/src/windows.rs | 346 | ||||
-rw-r--r-- | tokio-signal/tests/drop_multi_loop.rs | 39 | ||||
-rw-r--r-- | tokio-signal/tests/drop_then_get_a_signal.rs | 28 | ||||
-rw-r--r-- | tokio-signal/tests/dropping_does_not_deregister_other_instances.rs | 32 | ||||
-rw-r--r-- | tokio-signal/tests/multi_loop.rs | 40 | ||||
-rw-r--r-- | tokio-signal/tests/notify_both.rs | 27 | ||||
-rw-r--r-- | tokio-signal/tests/signal.rs | 20 | ||||
-rw-r--r-- | tokio-signal/tests/simple.rs | 20 | ||||
-rw-r--r-- | tokio-signal/tests/support.rs | 50 | ||||
-rw-r--r-- | tokio-signal/tests/twice.rs | 19 |
22 files changed, 1718 insertions, 0 deletions
diff --git a/tokio-signal/.travis.yml b/tokio-signal/.travis.yml new file mode 100644 index 00000000..fd408ebf --- /dev/null +++ b/tokio-signal/.travis.yml @@ -0,0 +1,29 @@ +language: rust +sudo: false + +matrix: + include: + - rust: stable + - os: osx + - rust: beta + - rust: nightly + + - rust: nightly + before_script: + - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH + script: + - cargo doc --no-deps --all-features + after_success: + - travis-cargo --only nightly doc-upload + +script: + - cargo test --no-fail-fast + - rustdoc --test README.md -L target/debug/deps + +env: + global: + - secure: "SXXK7Znvm1s5WWQ94l9IP25mXA0uGIQ7ghBuumZz3nSAfxhhJQnYi5hCAbl2/cOfSbpgEtE137dgk6Nd9UDx7rIkLCSe8TWyYjzraX/vvX3xNtLh/fjsayYYRK9a6qU2HIJegZdxPgyF5h2DeBgeLks0Ue8drrFQ1s9bYZVUO0yeuZ3aLkL1FkIG6RXGItUFpb6srEYL1NLizYLxXFEG3cL+kKoFIWc2qPx3EwOqv/eii134nQsuObhWZvPqfTo7zfNP8W/6TnoiggpRH1nrZc3DI3CynTICIOJ2Ogn9gFX9LftYKuJysSwUNVN3WF5aOuLP/XjRSBLYc+PW3v0iqiGzMX3n1VpcyhcbsSNA7ZckGn1HZsWYwspAxkN3idSuVie9Mezm7IV4005juiYKEWEr6hlkv1lzd49QZkWOvLCFCMRiwOOGp4NyzilG1Q1Zs3G1wrcvstmasNpK+QUFNdOFvT2sm34rI4x2rQUvjC/OyqbAK+PjYmTHL47YKON5ymfUL3mAcwgUfBUSd4Wpx8G3VKg3gMcmQm27ah1knOGJWH6XulYTnfGfx6bLo5t2NGx+vZk0naqajD3auWnseobMDsFjhUIRrt6GlnfPqeFoJSm0unu3riAX+RDF/iqZdDfjhX4evETIw3SaTl8EQtVLwz7kJTnxSbTU4XTi+0M=" + +notifications: + email: + on_success: never diff --git a/tokio-signal/CHANGELOG.md b/tokio-signal/CHANGELOG.md new file mode 100644 index 00000000..04688526 --- /dev/null +++ b/tokio-signal/CHANGELOG.md @@ -0,0 +1,41 @@ +# Changelog +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [0.2.5] - 2018-08-29 +### Fixes +* Fix a possible starvation when polling multiple `Signal` instances outside of +a tokio reactor (e.g. by using `Future::wait`) + +## [0.2.4] - 2018-08-25 +### Fixes +* Actually make `unix::bsd` public + +## [0.2.3] - 2018-08-25 +### Features +* Exposes `SIGINFO` on BSD-based operating systems. (#46) + +## [0.2.2] - 2018-08-14 +### Fixes +* Fix starvation of `Signal`s whenever a `Signal` instance is dropped +* Fix starvation of individual `Signal`s based on their creation order + +## [0.2.1] - 2018-05-27 +### Fixes +* Bump minimum supported version of `mio` to 0.6.14 + +## 0.2.0 - 2018-05-07 +#### Features + * Uses `tokio` instead of `tokio_core` (#24) + * Supports all 33 signals on FreeBSD (#27) + +[Unreleased]: https://github.com/alexcrichton/tokio-process/compare/0.2.5...HEAD +[0.2.5]: https://github.com/alexcrichton/tokio-signal/compare/0.2.4...0.2.5 +[0.2.4]: https://github.com/alexcrichton/tokio-signal/compare/0.2.3...0.2.4 +[0.2.3]: https://github.com/alexcrichton/tokio-signal/compare/0.2.2...0.2.3 +[0.2.2]: https://github.com/alexcrichton/tokio-signal/compare/0.2.1...0.2.2 +[0.2.1]: https://github.com/alexcrichton/tokio-signal/compare/0.2.0...0.2.1 diff --git a/tokio-signal/Cargo.toml b/tokio-signal/Cargo.toml new file mode 100644 index 00000000..b3118ef7 --- /dev/null +++ b/tokio-signal/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "tokio-signal" +version = "0.2.5" +authors = ["Alex Crichton <alex@alexcrichton.com>"] +license = "MIT/Apache-2.0" +repository = "https://github.com/alexcrichton/tokio-signal" +homepage = "https://github.com/alexcrichton/tokio-signal" +documentation = "https://docs.rs/tokio-signal/0.2" +description = """ +An implementation of an asynchronous Unix signal handling backed futures. +""" +categories = ["asynchronous"] + +[badges] +travis-ci = { repository = "alexcrichton/tokio-signal" } +appveyor = { repository = "alexcrichton/tokio-signal" } + +[dependencies] +futures = "0.1.11" +mio = "0.6.14" +tokio-reactor = "0.1.0" +tokio-executor = "0.1.0" +tokio-io = "0.1" + +[target.'cfg(unix)'.dependencies] +libc = "0.2" +mio-uds = "0.6" +signal-hook = "0.1" + +[dev-dependencies] +tokio-core = "0.1.17" +tokio = "0.1.6" + +[target.'cfg(windows)'.dependencies.winapi] +version = "0.3" +features = ["minwindef", "wincon"] diff --git a/tokio-signal/LICENSE-APACHE b/tokio-signal/LICENSE-APACHE new file mode 100644 index 00000000..16fe87b0 --- /dev/null +++ b/tokio-signal/LICENSE-APACHE @@ -0,0 +1,201 @@ + 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 [yyyy] [name of copyright owner] + +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. diff --git a/tokio-signal/LICENSE-MIT b/tokio-signal/LICENSE-MIT new file mode 100644 index 00000000..28e630cf --- /dev/null +++ b/tokio-signal/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2016 Alex Crichton + +Permission 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. diff --git a/tokio-signal/README.md b/tokio-signal/README.md new file mode 100644 index 00000000..cb62dfbf --- /dev/null +++ b/tokio-signal/README.md @@ -0,0 +1,58 @@ +# tokio-signal + +An implementation of Unix signal handling for Tokio + +[![Build Status](https://travis-ci.org/alexcrichton/tokio-signal.svg?branch=master)](https://travis-ci.org/alexcrichton/tokio-signal) + +[Documentation](https://docs.rs/tokio-signal) + +## Usage + +First, add this to your `Cargo.toml`: + +```toml +[dependencies] +tokio-signal = "0.2" +``` + +Next you can use this in conjunction with the `tokio` and `futures` crates: + +```rust,no_run +extern crate futures; +extern crate tokio; +extern crate tokio_signal; + +use futures::{Future, Stream}; + +fn main() { + + // Create an infinite stream of "Ctrl+C" notifications. Each item received + // on this stream may represent multiple ctrl-c signals. + let ctrl_c = tokio_signal::ctrl_c().flatten_stream(); + + // Process each ctrl-c as it comes in + let prog = ctrl_c.for_each(|()| { + println!("ctrl-c received!"); + Ok(()) + }); + + tokio::run(prog.map_err(|err| panic!("{}", err))); +} +``` + +# License + +This project is 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 tokio-signal by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff --git a/tokio-signal/appveyor.yml b/tokio-signal/appveyor.yml new file mode 100644 index 00000000..6067b9d2 --- /dev/null +++ b/tokio-signal/appveyor.yml @@ -0,0 +1,35 @@ +environment: + matrix: + # Stable channel + - TARGET: x86_64-pc-windows-gnu + CHANNEL: stable + - TARGET: x86_64-pc-windows-msvc + CHANNEL: stable + # Beta channel + - TARGET: x86_64-pc-windows-msvc + CHANNEL: beta + # Nightly channel + - TARGET: x86_64-pc-windows-msvc + CHANNEL: nightly + +# Install Rust and Cargo +# (Based on from https://github.com/rust-lang/libc/blob/master/appveyor.yml) +install: + - curl -sSf -o rustup-init.exe https://win.rustup.rs + - rustup-init.exe --default-host %TARGET% --default-toolchain %CHANNEL% -y + - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin + - rustc -Vv + - cargo -V + +# 'cargo test' takes care of building for us, so disable Appveyor's build stage. This prevents +# the "directory does not contain a project or solution file" error. +# source: https://github.com/starkat99/appveyor-rust/blob/master/appveyor.yml#L113 +build: false + +test_script: + - cargo build --example ctrl-c + - rustdoc --test README.md -L target/debug/deps + +branches: + only: + - master diff --git a/tokio-signal/examples/ctrl-c.rs b/tokio-signal/examples/ctrl-c.rs new file mode 100644 index 00000000..df821a3f --- /dev/null +++ b/tokio-signal/examples/ctrl-c.rs @@ -0,0 +1,63 @@ +extern crate futures; +extern crate tokio_core; +extern crate tokio_signal; + +use futures::{Future, Stream}; +use tokio_core::reactor::Core; + +/// how many signals to handle before exiting +const STOP_AFTER: u64 = 10; + +fn main() { + // set up a Tokio event loop + let mut core = Core::new().unwrap(); + + // tokio_signal provides a convenience builder for Ctrl+C + // this even works cross-platform: linux and windows! + // + // `fn ctrl_c()` produces a `Future` of the actual stream-initialisation + // the `flatten_stream()` convenience method lazily defers that + // initialisation, allowing us to use it 'as if' it is already the + // stream we want, reducing boilerplate Future-handling. + let endless_stream = tokio_signal::ctrl_c().flatten_stream(); + // don't keep going forever: convert the endless stream to a bounded one. + let limited_stream = endless_stream.take(STOP_AFTER); + + // how many Ctrl+C have we received so far? + let mut counter = 0; + + println!( + "This program is now waiting for you to press Ctrl+C {0} times. + * If running via `cargo run --example ctrl-c`, Ctrl+C also kills it, \ + due to https://github.com/rust-lang-nursery/rustup.rs/issues/806 + * If running the binary directly, the Ctrl+C is properly trapped. + Terminate by repeating Ctrl+C {0} times, or ahead of time by \ + opening a second terminal and issuing `pkill -sigkil ctrl-c`", + STOP_AFTER + ); + + // Stream::for_each is a powerful primitive provided by the Futures crate. + // It turns a Stream into a Future that completes after all stream-items + // have been completed, or the first time the closure returns an error + let future = limited_stream.for_each(|()| { + // Note how we manipulate the counter without any fancy synchronisation. + // The borrowchecker realises there can't be any conflicts, so the closure + // can just capture it. + counter += 1; + println!( + "Ctrl+C received {} times! {} more before exit", + counter, + STOP_AFTER - counter + ); + + // return Ok-result to continue handling the stream + Ok(()) + }); + + // Up until now, we haven't really DONE anything, just prepared + // now it's time to actually schedule, and thus execute, the stream + // on our event loop + core.run(future).unwrap(); + + println!("Stream ended, quiting the program."); +} diff --git a/tokio-signal/examples/multiple.rs b/tokio-signal/examples/multiple.rs new file mode 100644 index 00000000..38052318 --- /dev/null +++ b/tokio-signal/examples/multiple.rs @@ -0,0 +1,38 @@ +//! A small example of how to listen for two signals at the same time + +extern crate futures; +extern crate tokio_core; +extern crate tokio_signal; + +use futures::{Future, Stream}; +use tokio_core::reactor::Core; +use tokio_signal::unix::{Signal, SIGINT, SIGTERM}; + +fn main() { + let mut core = Core::new().unwrap(); + + // Create a stream for each of the signals we'd like to handle. + let sigint = Signal::new(SIGINT).flatten_stream(); + let sigterm = Signal::new(SIGTERM).flatten_stream(); + + // Use the `select` combinator to merge these two streams into one + let stream = sigint.select(sigterm); + + // Wait for a signal to arrive + println!("Waiting for SIGINT or SIGTERM"); + println!( + " TIP: use `pkill -sigint multiple` from a second terminal \ + to send a SIGINT to all processes named 'multiple' \ + (i.e. this binary)" + ); + let (item, _rest) = core.run(stream.into_future()).ok().unwrap(); + + // Figure out which signal we received + let item = item.unwrap(); + if item == SIGINT { + println!("received SIGINT"); + } else { + assert_eq!(item, SIGTERM); + println!("received SIGTERM"); + } +} diff --git a/tokio-signal/examples/sighup-example.rs b/tokio-signal/examples/sighup-example.rs new file mode 100644 index 00000000..e48e23ea --- /dev/null +++ b/tokio-signal/examples/sighup-example.rs @@ -0,0 +1,39 @@ +extern crate futures; +extern crate tokio_core; +extern crate tokio_signal; + +use futures::{Future, Stream}; +use tokio_core::reactor::Core; +use tokio_signal::unix::{Signal, SIGHUP}; + +fn main() { + // set up a Tokio event loop + let mut core = Core::new().unwrap(); + + // on Unix, we can listen to whatever signal we want, in this case: SIGHUP + let stream = Signal::new(SIGHUP).flatten_stream(); + + println!("Waiting for SIGHUPS (Ctrl+C to quit)"); + println!( + " TIP: use `pkill -sighup sighup-example` from a second terminal \ + to send a SIGHUP to all processes named 'sighup-example' \ + (i.e. this binary)" + ); + + // for_each is a powerful primitive provided by the Futures crate + // it turns a Stream into a Future that completes after all stream-items + // have been completed. + let future = stream.for_each(|the_signal| { + println!( + "*Got signal {:#x}* I should probably reload my config \ + or something", + the_signal + ); + Ok(()) + }); + + // Up until now, we haven't really DONE anything, just prepared + // now it's time to actually schedule, and thus execute, the stream + // on our event loop, and loop forever + core.run(future).unwrap(); +} diff --git a/tokio-signal/src/lib.rs b/tokio-signal/src/lib.rs new file mode 100644 index 00000000..29dc914c --- /dev/null +++ b/tokio-signal/src/lib.rs @@ -0,0 +1,147 @@ +//! Asynchronous signal handling for Tokio +//! +//! This crate implements asynchronous signal handling for Tokio, an +//! asynchronous I/O framework in Rust. The primary type exported from this +//! crate, `unix::Signal`, allows listening for arbitrary signals on Unix +//! platforms, receiving them in an asynchronous fashion. +//! +//! Note that signal handling is in general a very tricky topic and should be +//! used with great care. This crate attempts to implement 'best practice' for +//! signal handling, but it should be evaluated for your own applications' needs +//! to see if it's suitable. +//! +//! The are some fundamental limitations of this crate documented on the +//! `Signal` structure as well. +//! +//! # Examples +//! +//! Print out all ctrl-C notifications received +//! +//! ```rust,no_run +//! extern crate futures; +//! extern crate tokio_core; +//! extern crate tokio_signal; +//! +//! use tokio_core::reactor::Core; +//! use futures::{Future, Stream}; +//! +//! fn main() { +//! let mut core = Core::new().unwrap(); +//! +//! // Create an infinite stream of "Ctrl+C" notifications. Each item received +//! // on this stream may represent multiple ctrl-c signals. +//! let ctrl_c = tokio_signal::ctrl_c().flatten_stream(); +//! +//! // Process each ctrl-c as it comes in +//! let prog = ctrl_c.for_each(|()| { +//! println!("ctrl-c received!"); +//! Ok(()) +//! }); +//! +//! core.run(prog).unwrap(); +//! } +//! ``` +//! +//! Wait for SIGHUP on Unix +//! +//! ```rust,no_run +//! # extern crate futures; +//! # extern crate tokio_core; +//! # extern crate tokio_signal; +//! # #[cfg(unix)] +//! # mod foo { +//! # +//! extern crate futures; +//! extern crate tokio_core; +//! extern crate tokio_signal; +//! +//! use tokio_core::reactor::Core; +//! use futures::{Future, Stream}; +//! use tokio_signal::unix::{Signal, SIGHUP}; +//! +//! fn main() { +//! let mut core = Core::new().unwrap(); +//! +//! // Like the previous example, this is an infinite stream of signals +//! // being received, and signals may be coalesced while pending. +//! let stream = Signal::new(SIGHUP).flatten_stream(); +//! +//! // Convert out stream into a future and block the program +//! core.run(stream.into_future()).ok().unwrap(); +//! } +//! # } +//! # fn main() {} +//! ``` + +#![doc(html_root_url = "https://docs.rs/tokio-signal/0.2")] +#![deny(missing_docs)] + +extern crate futures; +extern crate mio; +extern crate tokio_executor; +extern crate tokio_io; +extern crate tokio_reactor; + +use std::io; + +use futures::stream::Stream; +use futures::{future, Future}; +use tokio_reactor::Handle; + +pub mod unix; +pub mod windows; + +/// A future whose error is `io::Error` +pub type IoFuture<T> = Box<Future<Item = T, Error = io::Error> + Send>; +/// A stream whose error is `io::Error` +pub type IoStream<T> = Box<Stream<Item = T, Error = io::Error> + Send>; + +/// Creates a stream which receives "ctrl-c" notifications sent to a process. +/// +/// In general signals are handled very differently across Unix and Windows, but +/// this is somewhat cross platform in terms of how it can be handled. A ctrl-c +/// event to a console process can be represented as a stream for both Windows +/// and Unix. +/// +/// This function binds to the default event loop. Note that +/// there are a number of caveats listening for signals, and you may wish to +/// read up on the documentation in the `unix` or `windows` module to take a +/// peek. +pub fn ctrl_c() -> IoFuture<IoStream<()>> { + ctrl_c_handle(&Handle::current()) +} + +/// Creates a stream which receives "ctrl-c" notifications sent to a process. +/// +/// In general signals are handled very differently across Unix and Windows, but +/// this is somewhat cross platform in terms of how it can be handled. A ctrl-c +/// event to a console process can be represented as a stream for both Windows +/// and Unix. +/// +/// This function receives a `Handle` to an event loop and returns a future +/// which when resolves yields a stream receiving all signal events. Note that +/// there are a number of caveats listening for signals, and you may wish to +/// read up on the documentation in the `unix` or `windows` module to take a +/// peek. +pub fn ctrl_c_handle(handle: &Handle) -> IoFuture<IoStream<()>> { + return ctrl_c_imp(handle); + + #[cfg(unix)] + fn ctrl_c_imp(handle: &Handle) -> IoFuture<IoStream<()>> { + let handle = handle.clone(); + Box::new(future::lazy(move || { + unix::Signal::with_handle(unix::libc::SIGINT, &handle) + .map(|x| Box::new(x.map(|_| ())) as Box<Stream<Item = _, Error = _> + Send>) + })) + } + + #[cfg(windows)] + fn ctrl_c_imp(handle: &Handle) -> IoFuture<IoStream<()>> { + let handle = handle.clone(); + // Use lazy to ensure that `ctrl_c` gets called while on an event loop + Box::new(future::lazy(move || { + windows::Event::ctrl_c_handle(&handle) + .map(|x| Box::new(x) as Box<Stream<Item = _, Error = _> + Send>) + })) + } +} diff --git a/tokio-signal/src/unix.rs b/tokio-signal/src/unix.rs new file mode 100644 index 00000000..fa2cba54 --- /dev/null +++ b/tokio-signal/src/unix.rs @@ -0,0 +1,385 @@ +//! Unix-specific types for signal handling. +//! +//! This module is only defined on Unix platforms and contains the primary +//! `Signal` type for receiving notifications of signals. + +#![cfg(unix)] + +pub extern crate libc; +extern crate mio; +extern crate mio_uds; +extern crate signal_hook; + +use std::io::{self, Error, ErrorKind}; +use std::io::prelude::*; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, Once, ONCE_INIT}; + +use self::libc::c_int; +use self::mio_uds::UnixStream; +use futures::future; +use futures::sync::mpsc::{channel, Receiver, Sender}; +use futures::{Async, AsyncSink, Future}; +use futures::{Poll, Sink, Stream}; +use tokio_reactor::{Handle, PollEvented}; +use tokio_io::IoFuture; + +pub use self::libc::{SIGUSR1, SIGUSR2, SIGINT, SIGTERM}; +pub use self::libc::{SIGALRM, SIGHUP, SIGPIPE, SIGQUIT, SIGTRAP}; + +/// BSD-specific definitions +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd", +))] +pub mod bsd { + #[cfg(any(target_os = "dragonfly |