-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path22 - Nonamed_pipes.cpp
132 lines (113 loc) · 2.93 KB
/
22 - Nonamed_pipes.cpp
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
struct CmdLine
{
char* value;
char* arguments;
CmdLine* next;
};
// Compilation:
// g++ "03 - Nonamed_pipes.cpp" -o nonamedpipes
// Task:
// Create a program which works just like the command below:
// $> who | sort | uniq -c | sort -nk1
void run(CmdLine* command)
{
const int numPipes = 3;
int i = 0;
// Create all pipes.
int pipefds[2*numPipes];
for(i = 0; i < (numPipes); i++)
{
if(pipe(pipefds + i*2) < 0)
{
printf("Couldn't create pipe %d\n", i + 1);
exit(EXIT_FAILURE);
}
}
int j = 0;
pid_t pid;
while(command)
{
pid = fork();
if(pid == 0)
{
//if not last command
if(command->next)
{
if(dup2(pipefds[j + 1], STDOUT_FILENO) < 0)
{
perror("dup2");
exit(EXIT_FAILURE);
}
}
//if not first command && j != 2*numPipes
if(j != 0 )
{
if(dup2(pipefds[j-2], STDIN_FILENO) < 0)
{
perror(" dup2");///j-2 0 j+1 1
exit(EXIT_FAILURE);
}
}
for(i = 0; i < 2*numPipes; i++)
{
close(pipefds[i]);
}
// Command with or without arguments.
if (command->arguments == NULL)
{
if( execlp(command->value, command->value, NULL) < 0 )
{
perror(command->value);
exit(EXIT_FAILURE);
}
}
else
{
if( execlp(command->value, command->value, command->arguments, NULL) < 0 )
{
perror(command->value);
exit(EXIT_FAILURE);
}
}
}
else if(pid < 0)
{
perror("error");
exit(EXIT_FAILURE);
}
command = command->next;
j+=2;
}
/* Parent closes the pipes and wait for children */
for(i = 0; i < 2 * numPipes; i++)
{
close(pipefds[i]);
}
int status;
for(i = 0; i < numPipes + 1; i++)
{
wait(&status);
}
}
int main(int argc, char** argv)
{
printf("Result of operation is the same like if you type\n$>who | sort | uniq -c | sort -nk1\n");
char sort[] = "sort";
char sortArg[] = "-nk1";
char uniq[] = "uniq";
char uniqArg[] = "-c";
char who[] = "who";
CmdLine command4 = { sort, sortArg, NULL };
CmdLine command3 = { uniq, uniqArg, &command4 };
CmdLine command2 = { sort, NULL, &command3 };
CmdLine command1 = { who, NULL, &command2 };
run(&command1);
return 0;
}