Przeglądaj źródła

Finished fork logic. Fixed mul_strings.

themultiplexer 8 lat temu
rodzic
commit
edb03cd3ad
1 zmienionych plików z 71 dodań i 42 usunięć
  1. 71
    42
      hw6/task1/src/main.rs

+ 71
- 42
hw6/task1/src/main.rs Wyświetl plik

3
 
3
 
4
 extern crate nix;
4
 extern crate nix;
5
 
5
 
6
-use nix::unistd::{fork, getpid, pipe, read, write};
6
+use nix::unistd::{fork, pipe, read, write};
7
 use nix::sys::wait::wait;
7
 use nix::sys::wait::wait;
8
 use std::str;
8
 use std::str;
9
 use nix::sys::wait::WaitStatus;
9
 use nix::sys::wait::WaitStatus;
10
 use nix::unistd::ForkResult::{Child, Parent};
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
 fn main() {
16
 fn main() {
13
 
17
 
14
     let arguments: Vec<String> = args().collect();
18
     let arguments: Vec<String> = args().collect();
15
 
19
 
16
-    const BUFFER_SIZE : usize = 256;
17
-
18
     if arguments.len() > 2 {
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
     } else {
76
     } else {
61
         println!("Correct usage: number number <number> ...");
77
         println!("Correct usage: number number <number> ...");
62
         process::exit(1)
78
         process::exit(1)
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
 /// Concats the two given String *references* and returns them as a String.
96
 /// Concats the two given String *references* and returns them as a String.
68
 fn concatenate_strings<'a>(s1: &'a str, s2: &'a str) -> String {
97
 fn concatenate_strings<'a>(s1: &'a str, s2: &'a str) -> String {
69
     s1.to_string() + s2
98
     s1.to_string() + s2
78
 }
107
 }
79
 
108
 
80
 /// Calculates the sum of the given Strings and returns them as a Result.
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
     let mut sum = 0;
111
     let mut sum = 0;
83
     for x in v {
112
     for x in v {
84
         match x.parse::<i32>() {
113
         match x.parse::<i32>() {
87
                     Some(y) => {
116
                     Some(y) => {
88
                         sum = y;
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
     Ok(sum)
125
     Ok(sum)
97
 }
126
 }
98
 
127
 
99
 /// Calculates the product of the given Strings and returns them as a Result.
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
     for x in v {
131
     for x in v {
103
         match x.parse::<i32>() {
132
         match x.parse::<i32>() {
104
             Ok(val) => {
133
             Ok(val) => {
106
                     Some(y) => {
135
                     Some(y) => {
107
                         prod = y;
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
     Ok(prod)
144
     Ok(prod)

Ładowanie…
Anuluj
Zapisz