diff --git a/Cargo.lock b/Cargo.lock index d25923a..c676255 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -122,6 +122,7 @@ name = "chapter12" version = "0.1.0" dependencies = [ "lib", + "signal-hook", ] [[package]] @@ -887,11 +888,21 @@ dependencies = [ "serde", ] +[[package]] +name = "signal-hook" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "470c5a6397076fae0094aaf06a08e6ba6f37acb77d3b1b91ea92b4d6c8650c39" +dependencies = [ + "libc", + "signal-hook-registry", +] + [[package]] name = "signal-hook-registry" -version = "1.3.0" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16f1d0fef1604ba8f7a073c7e701f213e056707210e9020af4528e0101ce11a6" +checksum = "e51e73328dc4ac0c7ccbda3a494dfa03df1de2f46018127f60c693f2648455b0" dependencies = [ "libc", ] diff --git a/chapter12/Cargo.toml b/chapter12/Cargo.toml index e37613d..79003e9 100644 --- a/chapter12/Cargo.toml +++ b/chapter12/Cargo.toml @@ -7,4 +7,12 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -lib = { path = "../lib" } \ No newline at end of file +lib = { path = "../lib" } +tokio = { version = "1.8.1", features = ["full"] } +signal-hook = "0.3.9" +signal-hook-tokio = { version = "0.3.0", features = ["futures-v0_3"] } +futures = "0.3.15" + +[[bin]] +name = "12_4" +path = "src/12_4/main.rs" diff --git a/chapter12/src/12_4/main.rs b/chapter12/src/12_4/main.rs new file mode 100644 index 0000000..55c38ca --- /dev/null +++ b/chapter12/src/12_4/main.rs @@ -0,0 +1,25 @@ +use futures::stream::StreamExt; +use signal_hook::consts::signal::*; +use signal_hook_tokio::Signals; +use std::io::Error; + +#[tokio::main] +async fn main() -> Result<(), Error> { + let signals: Signals = Signals::new(&[SIGINT, SIGTERM])?; + let handle = signals.handle(); + let mut signals = signals.fuse(); + + tokio::spawn(async move { + while let Some(signal) = signals.next().await { + match signal { + SIGINT => println!("SIGINT"), + SIGTERM => println!("SIGTERM"), + _ => unreachable!(), + } + } + }); + + handle.close(); + + Ok(()) +} diff --git a/chapter12/src/main.rs b/chapter12/src/main.rs deleted file mode 100644 index e7a11a9..0000000 --- a/chapter12/src/main.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - println!("Hello, world!"); -}