Преглед на файлове

Added pipe functionality.

themultiplexer преди 8 години
родител
ревизия
6efbff96bd
променени са 1 файла, в които са добавени 22 реда и са изтрити 15 реда
  1. 22
    15
      hw6/task1/src/main.rs

+ 22
- 15
hw6/task1/src/main.rs Целия файл

3
 
3
 
4
 extern crate nix;
4
 extern crate nix;
5
 
5
 
6
-use nix::unistd::{fork, getpid};
6
+use nix::unistd::{fork, getpid, pipe, read, write};
7
 use nix::sys::wait::wait;
7
 use nix::sys::wait::wait;
8
 use nix::sys::wait::WaitStatus;
8
 use nix::sys::wait::WaitStatus;
9
 use nix::unistd::ForkResult::{Child, Parent};
9
 use nix::unistd::ForkResult::{Child, Parent};
12
 
12
 
13
  let arguments: Vec<String> = args().collect();
13
  let arguments: Vec<String> = args().collect();
14
 
14
 
15
-    if arguments.len() != 0 {
16
-   
15
+    if arguments.len() > 2 {
16
+        let (reader, writer) = pipe().unwrap();
17
+        let msg = "hello from parent";
18
+        let pid = fork();
19
+        match pid {
20
+            Ok(Child) => {
21
+                let mut read_buf = [0u8; 32];
22
+                let bytes_read = read(reader, &mut read_buf).unwrap();
23
+                let msg_received = str::from_utf8(&read_buf[0..bytes_read]).unwrap();
24
+                println!("{} received from parent:{:?}", getpid(), msg_received);
25
+            }
17
 
26
 
18
-    let pid = fork();
19
-    match pid {
20
-        Ok(Child) => {
21
-            println!("hello, I am child (pid:{})", getpid());
22
-        }
27
+            Ok(Parent { child }) => {
28
+
29
+                println!("sending to child with pid:{}", child);
30
+                write(writer, msg.as_bytes()).unwrap();
23
 
31
 
24
-        Ok(Parent { child }) => {
25
-            if let Ok(ws) = wait() {
26
-                if let WaitStatus::Exited(child_pid, exit_code) = ws {
27
-                
32
+                if let Ok(ws) = wait() {
33
+                    if let WaitStatus::Exited(child_pid, exit_code) = ws {
34
+                        println!("Parent exits");
35
+                    }
28
                 }
36
                 }
29
             }
37
             }
30
-        }
31
 
38
 
32
-        Err(_) => {}
33
-    }
39
+            Err(_) => {}
40
+        }
34
 
41
 
35
 
42
 
36
 
43
 

Loading…
Отказ
Запис