-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipex.c
129 lines (118 loc) · 2.94 KB
/
pipex.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
125
126
127
128
129
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* pipex.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jkassand <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/27 01:29:54 by jkassand #+# #+# */
/* Updated: 2021/11/27 14:27:06 by jkassand ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
void ft_close(t_arg *arg, int *file, int num)
{
int i;
i = -1;
while (++i < num)
{
if (!arg->fd || !arg->fd[i])
continue ;
close(arg->fd[i][0]);
close(arg->fd[i][1]);
free(arg->fd[i]);
}
free(arg->fd);
arg->fd = NULL;
if (!file)
return ;
if (file[0])
close(file[0]);
if (file[1])
close(file[1]);
}
void ft_dup2(int i, int *file, t_cmd *cmd, t_arg *arg)
{
int dup2res;
dup2res = 0;
if (cmd->in)
dup2res = dup2(file[0], STDIN_FILENO);
else if (i && arg->fd)
dup2res = dup2(arg->fd[i - 1][0], STDIN_FILENO);
if (dup2res == -1)
ft_exit(errno, "dup2", arg);
if (cmd->out)
dup2res = dup2(file[1], STDOUT_FILENO);
else if (i < arg->num - 1 && arg->fd)
dup2res = dup2(arg->fd[i][1], STDOUT_FILENO);
if (dup2res == -1)
ft_exit(errno, "dup2", arg);
ft_close(arg, file, arg->num - 1);
}
static void ft_waitpid(pid_t *pid, int num, t_arg *arg)
{
int i;
int status;
i = -1;
while (++i < num)
waitpid(-1, &status, 0);
if (arg)
{
if (WIFEXITED(status))
arg->errnum = WEXITSTATUS(status);
else
arg->errnum = status + 128;
}
free(pid);
}
void set_signal(int i, t_cmd *cmd)
{
int num;
int ms;
num = 0;
while (num++ < i)
cmd = cmd->next;
if (!cmd->cmd || !cmd->cmd[0])
{
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
return ;
}
ms = 0;
if (ft_strlen(cmd->cmd[0]) > 9 && !ft_strcmp(\
&cmd->cmd[0][ft_strlen(cmd->cmd[0]) - 10], "/minishell"))
ms = 1;
if (ft_strcmp(cmd->cmd[0], "minishell") && !ms)
{
signal(SIGINT, sig_pipex);
signal(SIGQUIT, sig_pipex);
return ;
}
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
}
void pipex(t_arg *arg)
{
pid_t *pid;
int i;
pid = malloc(arg->num * sizeof(pid_t));
if (!pid)
ft_exit(errno, "malloc", arg);
i = -1;
while (++i < arg->num)
{
set_signal(i, arg->cmd);
pid[i] = fork();
if (pid[i] == 0)
child(i, arg);
if (pid[i] == -1)
{
arg->errnum = errno;
ft_close(arg, NULL, arg->num - 1);
ft_waitpid(pid, i, NULL);
ft_exit(arg->errnum, "fork", arg);
}
}
ft_close(arg, NULL, arg->num - 1);
ft_waitpid(pid, arg->num, arg);
}