-
Notifications
You must be signed in to change notification settings - Fork 0
/
execution.c
119 lines (110 loc) · 2.94 KB
/
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
114
115
116
117
118
119
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* execution.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: auspensk <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/08/20 15:38:09 by auspensk #+# #+# */
/* Updated: 2024/10/15 10:40:59 by auspensk ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
void exec_child(t_cmd *cmd, t_data *data)
{
if (!redirect(cmd, data))
{
if (!cmd->cmd)
return ;
check_command(cmd, data);
if (cmd->cmd_check != BIN)
path_not_found(cmd, data);
close(data->std_in);
if (!ft_strcmp (cmd->args[0], "minishell"))
iterate_shlvl(data);
execve(cmd->cmd, cmd->args, data->envp);
perror(cmd->cmd);
data->st_code = errno;
if (data->st_code == 13 || data->st_code == 22)
data->st_code = 126;
}
}
int child_process(t_cmd *cmd, t_data *data)
{
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
data->child = 1;
if (cmd->next)
{
close ((data->fd)[0]);
dup2((data->fd)[1], STDOUT_FILENO);
close (data->fd[1]);
}
check_builtin(cmd, data);
if (cmd->cmd_check != BLTN)
exec_child(cmd, data);
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(data->std_in);
exit(clean_exit(NULL, data->st_code, data));
}
int fork_function(t_cmd *cmd, t_data *data)
{
int pid;
pid = fork();
if (pid == -1)
return (clean_exit("failed to create child process\n", 1, data));
if (pid == 0)
return (child_process(cmd, data));
if (cmd->next)
{
close((data->fd)[1]);
dup2((data->fd)[0], STDIN_FILENO);
close((data->fd)[0]);
}
else
dup2(data->std_in, STDIN_FILENO);
if (new_pid(pid, data) != 0)
return (clean_exit("failed to malloc for pids\n", 1, data));
return (0);
}
void wait_loop(t_data *data)
{
int wstatus;
t_pids *cur_pid;
cur_pid = data->pids;
wstatus = 0;
while (cur_pid)
{
waitpid(cur_pid->pid, &wstatus, 0);
cur_pid = cur_pid->next;
}
if (WIFEXITED(wstatus))
data->st_code = WEXITSTATUS(wstatus);
else if (WIFSIGNALED(wstatus))
{
g_lastsignal = WTERMSIG(wstatus);
data->st_code = g_lastsignal + 128;
}
}
int execute_loop(t_data *data)
{
t_cmd *cmd;
g_lastsignal = 0;
cmd = data->cmd;
if (cmd && !cmd->next && check_builtin(cmd, data))
return (data->st_code);
while (cmd)
{
if (cmd->next)
{
if (pipe(data->fd) < 0)
return (clean_exit(strerror(errno), 1, data));
}
if (fork_function(cmd, data))
return (1);
cmd = cmd->next;
}
wait_loop(data);
return (0);
}