-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.c
More file actions
86 lines (78 loc) · 1.95 KB
/
utils.c
File metadata and controls
86 lines (78 loc) · 1.95 KB
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kikiz <kikiz@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/03/04 16:22:28 by kikiz #+# #+# */
/* Updated: 2025/03/09 18:46:26 by kikiz ### ########.fr */
/* */
/* ************************************************************************** */
#include "pipex.h"
void execute(char *argv, char **envp)
{
char **cmd;
char *path;
if (!argv || !*argv)
cnf(argv);
cmd = ft_split(argv, ' ');
path = find_path(cmd[0], envp);
command_check(argv);
if (cmd == NULL || cmd[0] == NULL)
cnf(argv);
if (!path)
{
free(path);
free_mem(cmd);
exit(1);
}
if (execve(path, cmd, envp) == -1)
{
ft_putstr_fd("pipex : command not found: ", 2);
ft_putendl_fd(argv, 2);
free_mem(cmd);
exit(127);
}
}
void cnf(char *argv)
{
ft_putstr_fd("pipex : command not found: ", 2);
ft_putendl_fd(argv, 2);
exit(127);
}
char *find_path(char *cmd, char **envp)
{
int i;
char **paths;
char *slash;
char *path;
i = 0;
while (ft_strncmp(envp[i], "PATH=", 5) != 0)
i++;
paths = ft_split(envp[i] + 5, ':');
i = 0;
while (paths[i])
{
slash = ft_strjoin(paths[i], "/");
path = ft_strjoin(slash, cmd);
free(slash);
if (access(path, F_OK | X_OK) == 0)
return (path);
free(path);
i++;
}
free_mem(paths);
return (cmd);
}
void free_mem(char **str)
{
int i;
i = 0;
while (str[i])
{
free(str[i]);
i++;
}
free(str);
}