-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipe.c
87 lines (79 loc) · 2.23 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
80
81
82
83
84
85
86
87
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* pipe.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fvieira <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/16 18:31:47 by fvieira #+# #+# */
/* Updated: 2023/02/16 18:31:48 by fvieira ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
void closefd(int *pfd, int mult)
{
int i;
i = 0;
while (i < mult * 2 - 2)
{
close(pfd[i]);
i++;
}
}
void child(t_prompt *every, int *pfd, int mult, int c)
{
close(every->fd);
every->fd = 1;
if (dup2(pfd[1], STDOUT_FILENO) < 0)
printf("error\n");
closefd(pfd, mult);
path(every, c);
exit(every->exit_stat);
}
void alt_child(t_prompt *every, int *pfd, int i[2], int c)
{
close(every->fd);
every->fd = 1;
dup2(pfd[i[0] + 1], STDOUT_FILENO);
if (dup2(pfd[i[0] - 2], STDIN_FILENO) < 0)
printf("ERROR\n");
closefd(pfd, i[1]);
path(every, c);
exit(every->exit_stat);
}
void parent(t_prompt *every, int *pfd, int i[2], int c)
{
close(STDIN_FILENO);
if (dup(pfd[i[0] - 2]) < 0)
printf("ERROR\n");
closefd(pfd, i[1]);
path(every, c);
exit(every->exit_stat);
}
void mult_pipes(t_prompt *every, int c, int *i)
{
pid_t pid;
int status;
int *pfd;
pfd = malloc(sizeof(int) * ((i[1] - 1) * 2));
while (++i[0] < i[1] - 1)
pipe(pfd + i[0] * 2);
if (fork() == 0)
child(every, pfd, i[1], c);
i[0] = 2;
while (i[1] > 1 && every->sep[++c] && every->sep[c][0] == '|')
{
if (fork() == 0)
alt_child(every, pfd, i, c);
i[0] += 2;
}
pid = fork();
if (pid == 0)
parent(every, pfd, i, c);
closefd(pfd, i[1]);
waitpid(pid, &status, 0);
every->exit_stat = status >> 8;
while (i[1]-- - 1 > 0)
waitpid(0, &status, 0);
free(pfd);
}