-
Notifications
You must be signed in to change notification settings - Fork 0
/
handle_execution.c
113 lines (104 loc) · 2.51 KB
/
handle_execution.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* handle_execution.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: almelo <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/25 15:54:04 by almelo #+# #+# */
/* Updated: 2023/03/17 11:53:29 by almelo ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
static void deep_free(char **envp)
{
size_t i;
i = 0;
while (envp[i])
{
free(envp[i]);
i++;
}
free(envp);
}
void handle_pipe(char **argv, char **envp, t_envl *env_lst, int *prevpipe)
{
pid_t pid;
int pipefd[2];
char *pathname;
pipe(pipefd);
pid = fork();
if (pid == 0)
{
close(pipefd[0]);
dup2(pipefd[1], STDOUT_FILENO);
close(pipefd[1]);
dup2(*prevpipe, STDIN_FILENO);
close(*prevpipe);
if (handle_builtin_cp(argv, envp) == -1)
{
pathname = get_pathname(argv, env_lst);
if (pathname)
{
if (execve(pathname, argv, envp) == -1)
exit(0);
}
}
exit(0);
}
else
{
close(pipefd[1]);
close(*prevpipe);
*prevpipe = pipefd[0];
}
}
void handle_last_cmd(char **argv, char **envp, t_envl *env_lst, int *prevpipe)
{
pid_t pid;
char *pathname;
pid = fork();
if (pid == 0)
{
dup2(*prevpipe, STDIN_FILENO);
close(*prevpipe);
if (handle_builtin_cp(argv, envp) == -1)
{
pathname = get_pathname(argv, env_lst);
if (pathname)
{
if (execve(pathname, argv, envp) == -1)
exit(0);
}
}
exit(0);
}
else
{
close(*prevpipe);
while (wait(NULL) != -1)
;
}
}
void handle_execution(t_tokenl *token_lst, t_envl *env_lst)
{
char **argv;
char **envp;
int prevpipe;
prevpipe = dup(STDIN_FILENO);
while (token_lst->head)
{
argv = get_next_argv(token_lst);
envp = list_to_envp(env_lst);
env_lst = handle_builtin_pp(argv, envp, env_lst);
if (token_lst->pipe_count > 0)
{
handle_pipe(argv, envp, env_lst, &prevpipe);
free(dequeue_token(token_lst));
}
else
handle_last_cmd(argv, envp, env_lst, &prevpipe);
free(argv);
deep_free(envp);
}
}