-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpipex_child.c
124 lines (112 loc) · 2.89 KB
/
pipex_child.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
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
/* ************************************************************************** */
/* */
/* :::::::: */
/* pipex_child.c :+: :+: */
/* +:+ */
/* By: sde-rijk <[email protected]> +#+ */
/* +#+ */
/* Created: 2021/12/13 10:15:26 by sde-rijk #+# #+# */
/* Updated: 2022/01/24 13:41:14 by sde-rijk ######## odam.nl */
/* */
/* ************************************************************************** */
#include "minishell.h"
#include "Libft/libft.h"
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
static int ft_child_process(t_pipe pipex, int *pipefd, \
t_env *s_env, t_part *parts);
static void ft_dup2(int first, int second);
pid_t ft_do_forks(t_pipe pipex, t_part *parts, t_env *s_env, int status)
{
pid_t child;
child = fork();
if (child < 0)
perror("Fork: ");
if (child == 0)
{
status = ft_child_process(pipex, pipex.pipefd, s_env, parts);
exit(status);
}
if (pipex.iter > 0)
{
close(pipex.pipefd[0]);
close(pipex.pipefd[1]);
}
return (child);
}
static int ft_child_process(t_pipe pipex, int *pipefd, \
t_env *s_env, t_part *parts)
{
int status;
if (pipex.iter == 0)
ft_dup2(STDIN_FILENO, pipefd[3]);
else if (pipex.iter == pipex.size - 1)
ft_dup2(pipefd[0], STDOUT_FILENO);
else
ft_dup2(pipefd[0], pipefd[3]);
if (pipex.iter != 0)
{
close(pipefd[0]);
close(pipefd[1]);
}
close(pipefd[2]);
close(pipefd[3]);
pipex.cmd_flag = ft_get_cmd_flag(parts, pipex, s_env, &status);
if (status)
exit(status);
if (pipex.cmd_flag[0].part)
status = is_built_in(pipex.cmd_flag[0].part, \
count_parts(pipex.cmd_flag), pipex.cmd_flag, s_env);
free(pipex.cmd_flag);
return (status);
}
static void ft_dup2(int first, int second)
{
if (dup2(first, STDIN_FILENO) < 0)
{
perror("dup2");
exit(errno);
}
if (dup2(second, STDOUT_FILENO) < 0)
{
perror("dup2");
exit(errno);
}
}
int ft_find_first_command(t_pipe pipex, t_part *parts)
{
int i;
int j;
j = 0;
i = 0;
while (j < pipex.iter)
{
if (is_pipe(parts[i]))
j++;
i++;
}
return (i);
}
t_part *ft_get_cmd_flag(t_part *parts, t_pipe pipex, \
t_env *s_env, int *status)
{
int i;
int j;
i = ft_find_first_command(pipex, parts);
j = 0;
*status = 0;
while (parts[i + j].part && !is_pipe(parts[i + j]))
{
if (ft_is_redir(parts[i + j]))
{
*status = ft_do_redir(parts, s_env, i + j);
if (*status)
return (NULL);
j++;
}
j++;
}
return (get_commands_between_pipes(parts + i, pipex, s_env));
}