Browse Source

Finished fork logic. Fixed mul_strings.

themultiplexer 8 years ago
parent
commit
edb03cd3ad
1 changed files with 71 additions and 42 deletions
  1. 71
    42
      hw6/task1/src/main.rs

+ 71
- 42
hw6/task1/src/main.rs View File

@@ -3,60 +3,76 @@ use std::process;
3 3
 
4 4
 extern crate nix;
5 5
 
6
-use nix::unistd::{fork, getpid, pipe, read, write};
6
+use nix::unistd::{fork, pipe, read, write};
7 7
 use nix::sys::wait::wait;
8 8
 use std::str;
9 9
 use nix::sys::wait::WaitStatus;
10 10
 use nix::unistd::ForkResult::{Child, Parent};
11
+use std::os::unix::io::RawFd;
12
+
13
+const BUFFER_SIZE : usize = 256;
14
+
11 15
 
12 16
 fn main() {
13 17
 
14 18
     let arguments: Vec<String> = args().collect();
15 19
 
16
-    const BUFFER_SIZE : usize = 256;
17
-
18 20
     if arguments.len() > 2 {
21
+        if let Ok((reader, writer)) = pipe(){
22
+            let numbers = arguments[1..].to_vec();
23
+
24
+            let pid = fork();
25
+            match pid {
26
+                Ok(Child) => {
27
+
28
+                    match read_from_pipe(reader) {
29
+                        Ok(msg_received) => {
30
+                            let vec = split_into_strings(&msg_received);
31
+
32
+                            let pid = fork();
33
+                            match pid {
34
+                                Ok(Child) => {
35
+                                    match sum_strings(vec) {
36
+                                        Ok(res) => println!("Sum = {}", res),
37
+                                        Err(e) => println!("{}", e),
38
+                                    }
39
+                                },
40
+                                Ok(Parent{..}) => {
41
+                                    if let Ok(ws) = wait() {
42
+                                        if let WaitStatus::Exited(_,_) = ws {
43
+                                            match mul_strings(vec) {
44
+                                                Ok(res) => println!("Mul = {}", res),
45
+                                                Err(e) => println!("{}", e),
46
+                                            }
47
+                                        }
48
+                                    }
49
+                                },
50
+                                Err(_) => println!("Fatal error: Fork failed"),
51
+                            }
52
+
53
+                        },
54
+                        Err(_) => {},
55
+                    }
19 56
 
20
-        let (reader, writer) = pipe().unwrap();
21
-        let numbers = arguments[1..].to_vec();
22
-
23
-        let pid = fork();
24
-        match pid {
25
-            Ok(Child) => {
26
-                let mut read_buf = [0u8; BUFFER_SIZE];
27
-                let bytes_read = read(reader, &mut read_buf).unwrap();
28
-                let msg_received = str::from_utf8(&read_buf[0 .. bytes_read]).unwrap();
29
-
30
-
31
-                match sum_strings(split_into_strings(msg_received)) {
32
-                    Ok(res) => {
33
-                        println!("{}", res)
34
-                    },
35
-                    Err(_) => {},
36
-                }
37
-
38
-                //let result = sum_strings(numbers);
39
-
40
-            }
41 57
 
42
-            Ok(Parent { child }) => {
43
-                for s in numbers {
44
-                    write(writer, concatenate_strings(s, " ").as_bytes());
45 58
                 }
46 59
 
60
+                Ok(Parent{..}) => {
61
+                    let mut args = String::new();
62
+                    for s in numbers {
63
+                        args = concatenate_strings(&args, &concatenate_strings(&s , " "));
64
+                    }
65
+                    println!("sending to children: {}", args);
66
+                    if let Err(_) = write(writer, args.as_bytes()) { println!("Broken pipe") }
47 67
 
48
-                if let Ok(ws) = wait() {
49
-                    if let WaitStatus::Exited(child_pid, exit_code) = ws {
50
-                        println!("Parent exits");
68
+                    if let Err(_) = wait() {
69
+                        println!("Waiting on children failed")
51 70
                     }
52 71
                 }
53
-            }
54 72
 
55
-            Err(_) => {}
73
+                Err(_) => {}
74
+            }
56 75
         }
57
-
58
-
59
-
60 76
     } else {
61 77
         println!("Correct usage: number number <number> ...");
62 78
         process::exit(1)
@@ -64,6 +80,19 @@ fn main() {
64 80
 
65 81
 }
66 82
 
83
+fn read_from_pipe(reader:RawFd) -> Result<String, String>{
84
+    let mut read_buf = [0u8; BUFFER_SIZE];
85
+    match read(reader, &mut read_buf){
86
+        Ok(bytes_read) => {
87
+            match str::from_utf8(&read_buf[0 .. bytes_read]) {
88
+                Ok(msg_received) => Ok(msg_received.to_string()),
89
+                Err(_) => Err("Couldn't read".to_string()),
90
+            }
91
+        },
92
+        Err(_) => Err("Couldn't read".to_string()),
93
+    }
94
+}
95
+
67 96
 /// Concats the two given String *references* and returns them as a String.
68 97
 fn concatenate_strings<'a>(s1: &'a str, s2: &'a str) -> String {
69 98
     s1.to_string() + s2
@@ -78,7 +107,7 @@ fn split_into_strings<'a>(s1: &'a str) -> Vec<String> {
78 107
 }
79 108
 
80 109
 /// Calculates the sum of the given Strings and returns them as a Result.
81
-fn sum_strings(v: Vec<&str>) -> Result<i32, &str> {
110
+fn sum_strings(v: Vec<String>) -> Result<i32, String> {
82 111
     let mut sum = 0;
83 112
     for x in v {
84 113
         match x.parse::<i32>() {
@@ -87,18 +116,18 @@ fn sum_strings(v: Vec<&str>) -> Result<i32, &str> {
87 116
                     Some(y) => {
88 117
                         sum = y;
89 118
                     }
90
-                    None => return Err("Overflow would happen in sum_strings()"),
119
+                    None => return Err("Overflow would happen in sum_strings()".to_string()),
91 120
                 }
92 121
             }
93
-            Err(_) => return Err("Given String is not a int"),
122
+            Err(_) => return Err("Given String is not a int".to_string()),
94 123
         }
95 124
     }
96 125
     Ok(sum)
97 126
 }
98 127
 
99 128
 /// Calculates the product of the given Strings and returns them as a Result.
100
-fn mul_strings(v: Vec<&str>) -> Result<i32, &str> {
101
-    let mut prod = 0;
129
+fn mul_strings(v: Vec<String>) -> Result<i32, String> {
130
+    let mut prod = 1;
102 131
     for x in v {
103 132
         match x.parse::<i32>() {
104 133
             Ok(val) => {
@@ -106,10 +135,10 @@ fn mul_strings(v: Vec<&str>) -> Result<i32, &str> {
106 135
                     Some(y) => {
107 136
                         prod = y;
108 137
                     }
109
-                    None => return Err("Overflow would happen in mul_strings()"),
138
+                    None => return Err("Overflow would happen in mul_strings()".to_string()),
110 139
                 }
111 140
             }
112
-            Err(_) => return Err("Given String is not a int"),
141
+            Err(_) => return Err("Given String is not a int".to_string()),
113 142
         }
114 143
     }
115 144
     Ok(prod)

Loading…
Cancel
Save