-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipe.c
79 lines (65 loc) · 1.61 KB
/
pipe.c
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
#include "header.h"
int pipe_func(char *cmd, int *job_pid, char **job_name)
{
char* pipe_commands[50]={NULL};
char *temp = strtok(cmd, "|\n");
char* temp2;
int i=0;
while (temp != NULL)
{
if (strlen(temp)){
pipe_commands[i++]=temp;
}
temp = strtok(NULL, "|");
}
int in = 0, initial_stdin, initial_stdout;
int fd[2];
initial_stdin = dup(0);
initial_stdout = dup(1);
temp = pipe_commands[i-1];
for(int j=0;j<i-1;j++)
{
if (pipe_commands[j] == NULL)
break;
if (pipe(fd) < 0)
perror("Piping Failed");
int pid = fork();
if (pid < 0)
perror("Fork Error");
else if (pid == 0)
{
if (in != 0)
{
dup2(in, 0);
close(in);
}
dup2(fd[1], 1);
close(fd[1]);
// other_func(pipe_commands[j], job_pid, job_name);
// pipe_commands[j] = strtok(pipe_commands[j], " \t\n");
redirect(pipe_commands[j],job_pid,job_name);
exit(0);
}
else
{
close(fd[1]);
wait(NULL);
in = fd[0];
}
}
if (in != 0)
{
dup2(in, 0);
close(in);
}
// other_func(temp, job_pid, job_name);
// temp = strtok(temp," \t\n");
redirect(temp, job_pid, job_name);
dup2(initial_stdin, 0);
if (initial_stdin != 0)
close(initial_stdin);
dup2(initial_stdout, 1);
if (initial_stdout != 1)
close(initial_stdout);
return 0;
}