Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
yabtaour
GitHub Repository: yabtaour/Minishell-42
Path: blob/main/execution/my_mess/my_exec.c
1407 views
1
/* ************************************************************************** */
2
/* */
3
/* ::: :::::::: */
4
/* my_exec.c :+: :+: :+: */
5
/* +:+ +:+ +:+ */
6
/* By: ssabbaji <[email protected]> +#+ +:+ +#+ */
7
/* +#+#+#+#+#+ +#+ */
8
/* Created: 2022/08/10 11:10:11 by ssabbaji #+# #+# */
9
/* Updated: 2022/10/03 15:31:22 by ssabbaji ### ########.fr */
10
/* */
11
/* ************************************************************************** */
12
13
#include "../../minishell.h"
14
15
char *generate_path(t_data *data, char **cmd, int i, int flag)
16
{
17
char *path;
18
19
path = NULL;
20
if (!flag)
21
{
22
path = ft_strjoin(data->paths[i], "/");
23
path = ft_strjoin(path, cmd[0]);
24
}
25
else if (flag == 1)
26
path = ft_strjoin(path, cmd[0]);
27
else
28
{
29
path = ft_strjoin(custom_getenv("PWD", data->lst_env), "/");
30
path = ft_strjoin(path, cmd[0]);
31
}
32
return (path);
33
}
34
35
int check_access(t_data *data, char **cmd, int i, int flag)
36
{
37
char *path;
38
int fd;
39
int size;
40
41
size = 0;
42
fd = 0;
43
path = NULL;
44
path = generate_path(data, cmd, i, flag);
45
fd = access(path, F_OK | X_OK);
46
size = count_cmds(cmd);
47
cmd[size] = NULL;
48
if (fd == -1)
49
return (0);
50
else
51
{
52
if (data->lst_cmd->fd_in != 0)
53
close(data->lst_cmd->fd_in);
54
if (data->lst_cmd->fd_out != 1)
55
close(data->lst_cmd->fd_out);
56
execve(path, cmd, data->env);
57
perror("execve() error");
58
}
59
free(path);
60
return (1);
61
}
62
63
void print_cmd_error(char *cmd, int flag)
64
{
65
if (flag)
66
{
67
ft_putstr_fd("bash :", 2);
68
ft_putstr_fd(cmd, 2);
69
ft_putstr_fd(": command not found\n", 2);
70
}
71
else
72
{
73
ft_putstr_fd("bash :", 2);
74
ft_putstr_fd(cmd, 2);
75
ft_putstr_fd(": No such file or directory\n", 2);
76
}
77
}
78
79
int check_nonabs(t_data *data, char **cmd)
80
{
81
int ret;
82
int i;
83
84
i = -1;
85
ret = 0;
86
if (check_path(data->lst_env))
87
{
88
data->paths = ft_split(custom_getenv("PATH", data->lst_env), ':');
89
while (data->paths[++i] && ret != 1)
90
ret = check_access(data, cmd, i, 0);
91
if (!ret)
92
{
93
print_cmd_error(cmd[0], 1);
94
return (0);
95
}
96
}
97
else if (!check_access(data, cmd, 0, 3))
98
{
99
print_cmd_error(cmd[0], 0);
100
return (0);
101
}
102
return (1);
103
}
104
105
int execution_2(t_data *data, t_cmd *lst_cmd)
106
{
107
char **cmd;
108
109
data->paths = NULL;
110
cmd = lst_cmd->cmd;
111
if (cmd[0][0] == '/' || cmd[0][0] == '.')
112
check_access(data, cmd, 0, 1);
113
if (check_nonabs(data, cmd))
114
g_vars.g_exit_stat = 0;
115
else
116
g_vars.g_exit_stat = 127;
117
return (g_vars.g_exit_stat);
118
}
119
120