-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpiping.c
More file actions
96 lines (81 loc) · 2.01 KB
/
Copy pathpiping.c
File metadata and controls
96 lines (81 loc) · 2.01 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
94
95
96
#include "headers.h"
#include "piping.h"
#include "cmdhandle.h"
int countPipes(char ** parsed, int args)
{
int i, counter = 0;
for(i = 0; i < args; i++)
{
if(parsed[i] == "|")
{
counter++;
}
}
return counter;
}
void piping(char ** parsed, char ** parsed2, int args)
{
int numpipes = countPipes(parsed, args);
if(numpipes == 0)
{
cmdhandle(parsed, args);
}
else
{
int pipefd[2];
pid_t p1, p2;
if (pipe(pipefd) < 0)
{
printf("\nPipe could not be initialized");
return;
}
p1 = fork();
if (p1 < 0)
{
printf("\nCould not fork");
return;
}
if (p1 == 0)
{
// Child 1 executing..
// It only needs to write at the write end
close(pipefd[0]);
dup2(pipefd[1], STDOUT_FILENO);
close(pipefd[1]);
if (execvp(parsed[0], parsed) < 0)
{
printf("\nCould not execute command 1..");
exit(0);
}
}
else
{
// Parent executing
p2 = fork();
if (p2 < 0)
{
printf("\nCould not fork");
return;
}
// Child 2 executing..
// It only needs to read at the read end
if (p2 == 0)
{
close(pipefd[1]);
dup2(pipefd[0], STDIN_FILENO);
close(pipefd[0]);
if (execvp(parsed2[0], parsed2) < 0)
{
printf("\nCould not execute command 2..");
exit(0);
}
}
else
{
// parent executing, waiting for two children
wait(NULL);
wait(NULL);
}
}
}
}