-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.c
99 lines (90 loc) · 2.29 KB
/
utils.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mouaammo <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/12/15 18:24:21 by mouaammo #+# #+# */
/* Updated: 2022/12/21 12:29:15 by mouaammo ### ########.fr */
/* */
/* ************************************************************************** */
#include "pipex.h"
char *free_all(char **ptr)
{
int i;
i = 0;
if (!ptr)
return (NULL);
while (ptr[i])
free(ptr[i++]);
free(ptr);
return (NULL);
}
char *check_path(char **paths, char *arv)
{
char *full_path;
int i;
char *initial_path;
i = -1;
if (!paths || !arv)
return (NULL);
if (ft_strnstr(arv, "./", 2))
return (ft_strdup(arv + 2));
if ((access(arv, F_OK) == 0 && ft_strchr(arv, '/'))
|| (access(arv, F_OK) == 0 && !ft_strchr(arv, '/')))
return (ft_strdup(arv));
else if (access(arv, F_OK) == -1 && ft_strchr(arv, '/'))
return (NULL);
while (paths[++i])
{
initial_path = paths[i];
paths[i] = ft_strjoin(initial_path, "/");
free(initial_path);
full_path = ft_strjoin(paths[i], arv);
if (access(full_path, F_OK) == 0)
return (full_path);
free(full_path);
}
return (NULL);
}
char *get_path(char **ev)
{
if (!ev)
return (NULL);
while (*ev)
{
if (ft_strncmp("PATH=", *ev, 5) == 0)
return (*ev + 5);
ev++;
}
return (NULL);
}
void error(void)
{
perror("\033[31mError\033[0m");
exit(EXIT_FAILURE);
}
void execute(char **env, char *av, int *fd)
{
char **args;
char *file;
char **paths;
int i;
i = -1;
if (!av || !env || !fd)
error();
close(fd[0]);
close(fd[1]);
args = ft_split(av, ' ');
paths = ft_split(get_path(env), ':');
file = check_path(paths, args[0]);
free_all(paths);
if (execve(file, args, NULL))
{
if (file)
free(file);
free_all(args);
error();
}
}