-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathms_get_cmd_path.c
94 lines (85 loc) · 2.03 KB
/
ms_get_cmd_path.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ms_get_cmd_path.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ybong <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/02 19:11:37 by sma #+# #+# */
/* Updated: 2021/09/20 15:00:59 by ybong ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
void split_free(char **array)
{
int i;
i = 0;
while (array[i])
{
free(array[i++]);
}
free(array);
}
static char **get_path(char **env)
{
char *cmds;
char **paths;
int i;
i = 0;
while (env[i])
{
if (ft_strncmp(env[i], "PATH=", 5) == 0)
{
cmds = env[i];
cmds += 5;
paths = ft_split(cmds, ':');
return (paths);
}
i++;
}
return (0);
}
static char *path_join(char **paths, char *cmds)
{
char *path;
char *temp;
int i;
int fd;
i = 0;
while (paths && paths[i])
{
temp = ft_strjoin(paths[i], "/");
path = ft_strjoin_free(temp, cmds);
fd = open(path, O_RDONLY);
if (fd > 0)
{
close(fd);
return (path);
}
free(path);
close(fd);
i++;
}
exit(127);
return (0);
}
void get_cmd_path(t_data *data)
{
char **paths;
paths = get_path(data->env);
data->cmd_args = ft_split(data->cmds[data->idx], ' ');
if (data->cmd_args[0][0] == '.' || data->cmd_args[0][0] == '/')
{
split_free(paths);
data->path = data->cmd_args[0];
return ;
}
data->path = path_join(paths, data->cmd_args[0]);
if (data->path != 0)
{
split_free(paths);
return ;
}
split_free(data->cmds);
split_free(paths);
}