-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor_utils3.c
More file actions
100 lines (93 loc) · 2.47 KB
/
executor_utils3.c
File metadata and controls
100 lines (93 loc) · 2.47 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
97
98
99
100
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* executor_utils3.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yucchen <yucchen@student.42singapore.sg +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2026/01/08 16:47:41 by yucchen #+# #+# */
/* Updated: 2026/01/09 14:54:29 by yucchen ### ########.fr */
/* */
/* ************************************************************************** */
#include "parser.h"
static int count_cmds(t_cmd *cmd)
{
int cnt;
cnt = 0;
while (cmd)
{
cnt++;
cmd = cmd->next;
}
return (cnt);
}
int pipex_init(t_pipex *pipex, t_cmd *cmd_list, t_env **env, char **envp)
{
pipex->head = cmd_list;
pipex->cur = cmd_list;
pipex->env = env;
pipex->envp = envp;
pipex->cnt = count_cmds(cmd_list);
pipex->pids = malloc(pipex->cnt * sizeof(pid_t));
if (!pipex->pids)
return (0);
pipex->i = 0;
pipex->prev_read = -1;
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
return (1);
}
int pipex_open_pipe(t_pipex *pipex)
{
if (pipex->is_last)
return (1);
if (pipe(pipex->pipefd) == -1)
{
if (pipex->prev_read != -1)
close(pipex->prev_read);
perror("pipe");
free(pipex->pids);
return (0);
}
return (1);
}
void fork_fail(int is_last, int pipefd[2], int prev_read, pid_t *pids)
{
if (!is_last)
{
close(pipefd[0]);
close(pipefd[1]);
}
if (prev_read != -1)
close(prev_read);
perror("fork");
free(pids);
}
void child_process(t_pipex *pipex)
{
free(pipex->pids);
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
if (pipex->prev_read != -1)
{
if (dup2(pipex->prev_read, STDIN_FILENO) == -1)
{
perror("dup2 prev_read");
child_cleanup(pipex->head, pipex->env, pipex->envp);
exit(EXIT_FAILURE);
}
close(pipex->prev_read);
}
if (!pipex->is_last)
{
close(pipex->pipefd[0]);
if (dup2(pipex->pipefd[1], STDOUT_FILENO) == -1)
{
perror("dup2 pipe write");
child_cleanup(pipex->head, pipex->env, pipex->envp);
exit(EXIT_FAILURE);
}
close(pipex->pipefd[1]);
}
exec_child_cmd(pipex->cur, pipex->env, pipex->envp, pipex->head);
}