-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpipe_average.cpp
More file actions
85 lines (77 loc) · 1.67 KB
/
pipe_average.cpp
File metadata and controls
85 lines (77 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <sys/wait.h>
#include <unistd.h>
#include <vector>
#include <iostream>
#include <string>
#include <array>
#include <algorithm>
bool pipeRead(int pipe, int& value)
{
int readed = 0;
readed = read(pipe, &value, sizeof(value));
if (readed == -1)
{
perror("Error reading pipe.");
exit(EXIT_FAILURE);
}
else
if (readed == 0)
return false;
return true;
}
void pipeWrite(int pipe, int value)
{
if (write(pipe, &value, sizeof(value)) == -1)
{
perror("Error writing pipe.");
exit(EXIT_FAILURE);
}
}
std::vector<std::array<int, 2>> createPipes(int count)
{
std::vector<std::array<int, 2>> pipes;
for (int i = 0; i < count; ++i)
{
std::array<int, 2> newPipe;
int* data = newPipe.data(); // data is the pointer to a 2-element table of int
if (pipe(newPipe.data()) == -1)
{
perror("Error creating pipe.");
exit(EXIT_FAILURE);
}
pipes.push_back(newPipe);
}
return pipes;
}
// TODO add second child processy, that will be a proxy to pass the numbers and that will count the average (displayed after receiving all the numbers)
int main(int argc, char* argv[])
{
auto pipes = createPipes(2);
if (fork() == 0)
{
// child
close(pipes[0][0]);
close(pipes[1][0]);
close(pipes[1][1]);
int value;
do
{
std::cin >> value;
if (value > 0)
pipeWrite(pipes[0][1], value);
} while (value > 0);
close(pipes[0][1]);
}
else
{
// parent
close(pipes[0][1]);
close(pipes[1][0]);
close(pipes[1][1]);
int value;
while (pipeRead(pipes[0][0], value))
std::cout << "(Parent:" << getpid() << "):" << value << "\n";
close(pipes[0][0]);
}
return 0;
}