-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexec_command.c
More file actions
121 lines (110 loc) · 2.81 KB
/
Copy pathexec_command.c
File metadata and controls
121 lines (110 loc) · 2.81 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* exec_command.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cassius <cassius@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/04/01 21:12:19 by caqueiro #+# #+# */
/* Updated: 2024/11/28 19:30:00 by cassius ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
static void exec_command(t_main *main);
static void handle_main_process(t_token **t, t_main *main);
static void handle_child_process(t_main *main, pid_t *last);
static void consume_to_next_cmd(t_token **t, t_main *main);
void exec_all_commands(t_main *main)
{
t_token *t;
pid_t pid;
int status;
pid_t last;
t = main->token_lst->head;
pre_exec(main->token_lst);
while (t)
{
if (t && t->type == COMMAND)
{
if (!builtins(main))
handle_child_process(main, &last);
handle_main_process(&t, main);
}
else
consume_to_next_cmd(&t, main);
}
pid = waitpid(-1, &status, 0);
while (pid > 0)
{
if (pid == last)
update_status(status, main->envs);
pid = waitpid(-1, &status, 0);
}
setup_sigaction_handler();
}
static void handle_child_process(t_main *main, pid_t *last)
{
t_token *t;
t = main->token_lst->head->next;
while (t && t->type != COMMAND)
t = t->next;
if (!t)
{
*last = fork();
if (*last == 0)
{
setup_sigaction_child();
exec_command(main);
exit(0);
}
else
return ;
}
if (fork() == 0)
{
setup_sigaction_child();
exec_command(main);
exit(0);
}
}
static void exec_command(t_main *main)
{
char **args;
char *path;
t_token *t;
if (main->token_lst->head->type != COMMAND)
return ;
args = build_args(main);
path = absolute_path(main);
if (!path)
{
ft_printf("%s: command not found\n", main->token_lst->head->word);
exit(127);
}
dup_and_close(main->token_lst->head);
t = main->token_lst->head;
while (t)
{
close_not_used_fd(t);
t = t->next;
}
execve(path, args, to_envp(main->envs));
}
static void handle_main_process(t_token **t, t_main *main)
{
close_not_used_fd(*t);
consume_to_next_cmd(t, main);
}
static void consume_to_next_cmd(t_token **t, t_main *main)
{
t_token *tmp;
tmp = (*t)->next;
consume_token(main->token_lst, *t);
*t = tmp;
while (*t && (*t)->type != COMMAND)
{
tmp = (*t)->next;
consume_token(main->token_lst, *t);
*t = tmp;
}
}