-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexec_cmds.c
83 lines (77 loc) · 2.19 KB
/
exec_cmds.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* exec_cmds.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: emohamed <emohamed@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/09/17 18:37:07 by haarab #+# #+# */
/* Updated: 2023/10/01 08:55:26 by emohamed ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
char *get_path(t_vars *vars, char *cmd)
{
struct stat file_info;
char **path;
char *res;
char *temper1;
char *fullcmd;
vars->i = 0;
if (ft_strchr(cmd, '/'))
return (cmd);
res = ft_getenv("PATH", vars);
if (res == NULL)
return (NULL);
path = ft_split(res, ':');
while (path[vars->i])
{
temper1 = ft_strjoin(path[vars->i], "/");
fullcmd = ft_strjoin(temper1, cmd);
if (stat(fullcmd, &file_info) == 0)
return (fullcmd);
vars->i++;
}
return (NULL);
}
void comande_exec(t_vars *vars, int i, char *path, char *exp)
{
if (!path && vars->here_fd)
{
close(vars->here_fd);
exit(0);
}
if (vars->here_fd)
{
dup2(vars->here_fd, 0);
close(vars->here_fd);
vars->here_fd = 0;
}
if (path == NULL && !vars->cmds[i].has_redirections)
{
ft_putstr_fd("minishell : ", 2);
ft_putstr_fd(exp, 2);
ft_putstr_fd(": command not found\n", 2);
exit(127);
}
if (!execve(path, vars->cmds[i].cmds_args, vars->envp))
{
ft_putstr_fd("minishell: No such file or directory\n", 2);
exit(127);
}
}
void exec_cmds(t_vars *vars, int i)
{
int id;
char *path;
char *exp;
exp = ft_strtrim(vars->cmds[i].cmd, "\'");
path = get_path(vars, exp);
id = fork();
if (id == 0)
{
comande_exec(vars, i, path, exp);
}
waitpid(id, &g_exit_status, 0);
g_exit_status = WEXITSTATUS(g_exit_status);
}