Przeglądaj źródła

Added pipe functionality.

themultiplexer 8 lat temu
rodzic
commit
6efbff96bd
1 zmienionych plików z 22 dodań i 15 usunięć
  1. 22
    15
      hw6/task1/src/main.rs

+ 22
- 15
hw6/task1/src/main.rs Wyświetl plik

@@ -3,7 +3,7 @@ use std::process;
3 3
 
4 4
 extern crate nix;
5 5
 
6
-use nix::unistd::{fork, getpid};
6
+use nix::unistd::{fork, getpid, pipe, read, write};
7 7
 use nix::sys::wait::wait;
8 8
 use nix::sys::wait::WaitStatus;
9 9
 use nix::unistd::ForkResult::{Child, Parent};
@@ -12,25 +12,32 @@ fn main() {
12 12
 
13 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
 

Ładowanie…
Anuluj
Zapisz