42_minishell/utils/ft_get_executable.c

84 lines
1.6 KiB
C
Raw Normal View History

#include "./utils.h"
#include <unistd.h>
2023-03-20 10:31:39 -04:00
char *ft_get_executable_with_path(t_data *data, const char *name)
{
char *path;
2023-03-10 07:34:23 -05:00
if (access(name, F_OK) != 0)
{
2023-03-20 10:31:39 -04:00
data->exit_code = 127;
ft_eprintf("minishell: %s bash: No such file or directery\n");
return (NULL);
}
if (access(name, X_OK) != 0)
{
2023-03-20 10:31:39 -04:00
data->exit_code = 126;
ft_eprintf("minishell: %s: permission denied\n", name);
return (NULL);
}
path = ft_strdup(name);
if (path == NULL)
{
ft_eprintf("minishell: malloc failed\n");
return (NULL);
}
return (path);
}
2023-03-20 10:31:39 -04:00
char *ft_get_executable_without_path(t_data *data, const char *name)
{
char **tab;
char *paths;
char *path;
size_t i;
path = NULL;
2023-03-20 10:31:39 -04:00
paths = get_value_by_key("PATH", data->env);
if (paths == NULL)
2023-03-20 07:41:40 -04:00
{
2023-03-20 10:31:39 -04:00
data->exit_code = 127;
2023-03-20 07:41:40 -04:00
ft_eprintf("minishell: %s: command not found\n", name);
return (NULL);
}
tab = ft_split(paths, ':');
if (tab == NULL)
{
ft_eprintf("minishell: malloc failed\n");
return (NULL);
}
i = 0;
while (tab[i] != NULL)
{
path = ft_strmerger(3, tab[i], "/", name);
if (path == NULL)
{
ft_eprintf("minishell: malloc failed\n");
break;
}
2023-03-10 07:34:23 -05:00
if (access(path, X_OK) == 0)
break;
free(path);
path = NULL;
i++;
}
ft_freer_tab_ultimate(1, tab);
if (path == NULL)
2023-03-20 10:31:39 -04:00
{
data->exit_code = 127;
ft_eprintf("minishell: %s: command not found\n", name);
2023-03-20 10:31:39 -04:00
}
return (path);
}
2023-03-20 10:31:39 -04:00
char *ft_get_executable(t_data *data, const char *name)
{
char *path;
if (name[0] == '.' || name[0] == '/')
2023-03-20 10:31:39 -04:00
path = ft_get_executable_with_path(data, name);
else
2023-03-20 10:31:39 -04:00
path = ft_get_executable_without_path(data, name);
return (path);
}