-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpath.c
71 lines (64 loc) · 2.14 KB
/
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* path.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: phelebra <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/08/01 16:43:48 by phelebra #+# #+# */
/* Updated: 2023/08/07 15:52:36 by phelebra ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
#define PATH_SEP ":"
extern int g_status;
// Gets PATH environment variable and saves into path_env
// Loops through each directory in path_env separated by PATH_SEP
// Uses get_path_token function to get full path, returns it
char *get_path(char *cmd, t_env *env)
{
int cmd_len;
char *path_env;
char *path;
path_env = NULL;
cmd_len = ft_strlen(cmd);
while (env != NULL)
{
if (ft_strncmp(env->key, "PATH", 4) == 0)
{
path_env = ft_strdup(env->value);
break ;
}
env = env->next;
}
if (path_env == NULL)
return (NULL);
path = get_path_token(cmd, path_env, cmd_len);
return (path);
}
// Searches through each path in the PATH environment variable
// Construct the full path to the command
// Uses access() to check if path is executable
// Returns it if it is
char *get_path_token(char *cmd, char *path_env, int cmd_len)
{
char *path_token;
char *path;
path_token = ft_strtok(path_env, PATH_SEP);
while (path_token != NULL)
{
path = ft_calloc(ft_strlen(path_token) + cmd_len + 2, 1);
ft_strcat(path, path_token);
ft_strcat(path, "/");
ft_strcat(path, cmd);
if (access (path, X_OK) == 0)
{
free(path_env);
return (path);
}
free(path);
path_token = ft_strtok(NULL, PATH_SEP);
}
free(path_env);
return (NULL);
}