-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpipe.c
More file actions
93 lines (92 loc) · 2.24 KB
/
pipe.c
File metadata and controls
93 lines (92 loc) · 2.24 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
86
87
88
89
90
91
92
93
#include"headers.h"
void exec_pipe(char *command){
int i = 0;
char *pipe_args[MAX_BUFF], *token, *arg[1000][1000];
token = strtok(command, "|");
pipe_args[i] = token;
i++;
while(token != NULL){
token = strtok(NULL, "|");
pipe_args[i] = token;
i++;
}
pipe_args[i] = NULL;
int j = 0, k = 0, len = i - 1;
i = 0;
while(i < len){
j = 0;
token = strtok(pipe_args[i], " ");
arg[i][j] = token;
j++;
while(token != NULL){
token = strtok(NULL, " ");
arg[i][j] = token;
j++;
}
arg[i][j] = NULL;
i++;
}
int fd1[2], fd2[2];
for(i = 0; i < len; i++){
if(i % 2 == 0){
if(pipe(fd1) < 0) {
perror("Error");
return;
}
pid_t p1 = fork();
if(p1 < 0){
perror("Forking failed");
return;
}
else if(p1 == 0){
if (i != 0){
dup2(fd2[0], STDIN_FILENO);
}
if (i != len - 1){
dup2(fd1[1], STDOUT_FILENO);
}
if(execvp(arg[i][0], arg[i]) < 0){
perror("Error in executing the command");
return;
}
}
else{
if(i != 0){
close(fd2[0]);
}
if (i != len - 1){
close(fd1[1]);
}
wait(NULL);
}
}
else{
if(pipe(fd2) < 0){
perror("Error");
return;
}
pid_t p1 = fork();
if(p1 < 0){
perror("Forking failed");
return;
}
else if(p1 == 0){
dup2(fd1[0], STDIN_FILENO);
if(i != len - 1){
dup2(fd2[1], STDOUT_FILENO);
}
if(execvp(arg[i][0], arg[i]) < 0){
perror("Error in executing the command");
return;
}
}
else{
close(fd1[0]);
if (i != len - 1){
close(fd2[1]);
}
}
wait(NULL);
}
}
}