diff --git a/Chapter08/Cargo.toml b/Chapter08/Cargo.toml index b5794ba..0143bfc 100644 --- a/Chapter08/Cargo.toml +++ b/Chapter08/Cargo.toml @@ -4,6 +4,7 @@ version = "1.0.0" [dependencies] nix = "0.10" +thread-id = "3.3" [[bin]] name = "process_a" @@ -24,3 +25,15 @@ path = "fork2.rs" [[bin]] name = "fork3" path = "fork3.rs" + +[[bin]] +name = "thread1" +path = "thread1.rs" + +[[bin]] +name = "thread2" +path = "thread2.rs" + +[[bin]] +name = "thread3" +path = "thread3.rs" diff --git a/Chapter08/thread1.rs b/Chapter08/thread1.rs new file mode 100644 index 0000000..1a5aacb --- /dev/null +++ b/Chapter08/thread1.rs @@ -0,0 +1,21 @@ +use std::{thread,time}; +use std::process; +extern crate thread_id; + +fn main() { + for _ in 0..3 { + thread::spawn(|| { + let t = time::Duration::from_millis(1000); + loop { + println!("child thread #{}:{}", process::id(), thread_id::get()); + thread::sleep(t); + } + }); + } + + let t = time::Duration::from_millis(1000); + loop { + println!("parent thread #{}:{}", process::id(), thread_id::get()); + thread::sleep(t); + } +} diff --git a/Chapter08/thread2.rs b/Chapter08/thread2.rs new file mode 100644 index 0000000..f86e416 --- /dev/null +++ b/Chapter08/thread2.rs @@ -0,0 +1,23 @@ +extern crate nix; +use nix::unistd::{fork}; +use std::{thread,time}; + +fn main() { + let mut big_data: Vec = Vec::with_capacity(200000000); + big_data.push(1); + big_data.push(2); + big_data.push(3); + + //Both sides of the fork, will continue to fork + //This is called a fork bomb + for _ in 0..9 { + fork().expect("fork failed"); + } + //2^9 = 512 + + let t = time::Duration::from_millis(1000); + loop { + big_data[2]; + thread::sleep(t); + } +} diff --git a/Chapter08/thread3.rs b/Chapter08/thread3.rs new file mode 100644 index 0000000..a764283 --- /dev/null +++ b/Chapter08/thread3.rs @@ -0,0 +1,36 @@ +extern crate nix; +use nix::unistd::{fork,ForkResult}; +use std::{thread,time}; +use std::process; +use std::io::prelude::*; +use std::net::TcpListener; + +fn serve(listener: TcpListener) -> ! { + for stream in listener.incoming() { + let mut buffer = [0; 2048]; + let mut tcp = stream.unwrap(); + tcp.read(&mut buffer).expect("tcp read failed"); + let response = format!("respond from #{}\n", process::id()); + tcp.write(response.as_bytes()).expect("tcp write failed"); + } + panic!("unreachable"); +} + +fn main() { + let listener = TcpListener::bind("127.0.0.1:8888").unwrap(); + let mut children = Vec::new(); + + for _ in 0..3 { + match fork().expect("fork failed") { + ForkResult::Parent{ child: pid } => { children.push(pid); } + ForkResult::Child => { + serve(listener) + } + } + } + + let t = time::Duration::from_millis(1000); + loop { + thread::sleep(t); + } +}