-
Notifications
You must be signed in to change notification settings - Fork 0
/
execution.c
executable file
·88 lines (78 loc) · 1.73 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
#include "minishell.h"
int matrix_len(char **matrix)
{
int i;
i = 0;
if (!matrix)
return (0);
while (matrix[i])
i++;
return (i);
}
char *test_path(t_list *cmd)
{
char **new_path;
char *env_path;
env_path = ft_get_env(cmd->envp->env, "PATH");
if (!env_path)
return (NULL);
new_path = ft_split(env_path + 5, ':');
return (test_access(new_path, cmd->cmd));
}
char *test_access(char **path, char **cmd)
{
char *temp;
char *cmd_path;
int i;
i = -1;
while (path[++i])
{
if (access(cmd[0], F_OK | X_OK) == 0)
return (cmd[0]);
temp = ft_strjoin(path[i], "/");
cmd_path = ft_strjoin(temp, cmd[0]);
free(temp);
if (access(cmd_path, F_OK | X_OK) == 0)
return (cmd_path);
free(cmd_path);
}
return (0);
}
DIR *check_cmd(t_list *cmds)
{
DIR *dir;
char **s;
dir = NULL;
if (cmds->cmd && cmds->cmd[0])
dir = opendir(cmds->cmd[0]);
if (cmds->cmd && cmds->cmd[0] && ft_strchr(cmds->cmd[0], '/') && !dir)
{
s = ft_split(cmds->cmd[0], '/');
cmds->cmd_path = ft_strdup(cmds->cmd[0]);
cmds->cmd[0] = s[matrix_len(s) - 1];
free(s);
}
else if (cmds->cmd && cmds->cmd[0] && !dir)
{
cmds->cmd_path = test_path(cmds);
if (!cmds || !cmds->cmd[0] || !cmds->cmd[0][0])
ft_perror(127, NULL, 1);
}
return (dir);
}
int get_path(t_list *cmds)
{
DIR *dir;
dir = check_cmd(cmds);
if (!is_builtin(cmds->cmd) && dir && cmds && cmds->cmd_path)
return (ft_perror(126, cmds->cmd[0], 0));
else if (!is_builtin(cmds->cmd) && cmds && cmds->cmd_path
&& access(cmds->cmd_path, F_OK) == -1)
return (ft_perror(127, cmds->cmd_path, 0));
else if (!is_builtin(cmds->cmd) && cmds && cmds->cmd_path
&& access(cmds->cmd_path, X_OK) == -1)
return (ft_perror(126, cmds->cmd[0], 1));
if (dir)
closedir(dir);
return (0);
}