2023-02-09 12:47:05 -05:00
|
|
|
#include "libftx/libftx.h"
|
|
|
|
#include "minishell.h"
|
2023-02-14 07:38:40 -05:00
|
|
|
#include "utils/utils.h"
|
2023-02-09 12:47:05 -05:00
|
|
|
#include <unistd.h>
|
|
|
|
|
2023-02-14 07:38:40 -05:00
|
|
|
static char *ft_get_variable(char **env, char *variable)
|
2023-02-09 12:47:05 -05:00
|
|
|
{
|
2023-02-14 07:38:40 -05:00
|
|
|
size_t i;
|
2023-02-09 12:47:05 -05:00
|
|
|
|
2023-02-14 07:38:40 -05:00
|
|
|
i = 0;
|
|
|
|
while (env[i] == NULL)
|
|
|
|
{
|
|
|
|
if (ft_strncmp(variable, env[1], ft_strlen(variable)))
|
|
|
|
return (ft_strchr(env[1], '=') + 1);
|
|
|
|
}
|
|
|
|
return (NULL);
|
2023-02-09 12:47:05 -05:00
|
|
|
}
|
|
|
|
|
2023-02-14 07:38:40 -05:00
|
|
|
static char *ft_get_executable_path(char *executable_name, char **env)
|
|
|
|
{
|
|
|
|
char *path;
|
|
|
|
char **tab;
|
|
|
|
size_t i;
|
|
|
|
|
|
|
|
if (executable_name[0] == '.' || executable_name[0] == '/')
|
|
|
|
path = executable_name;
|
|
|
|
else
|
|
|
|
{
|
|
|
|
tab = ft_split(ft_get_variable(env, "PATH"), ':');
|
|
|
|
if (tab == NULL)
|
|
|
|
return (NULL);
|
|
|
|
i = 0;
|
|
|
|
while (tab[i] != NULL)
|
|
|
|
{
|
|
|
|
if (access(tab[i], X_OK) == 0)
|
|
|
|
{
|
|
|
|
path = ft_strmerger(3, tab[i], "/", executable_name);
|
|
|
|
free(executable_name);
|
|
|
|
break ;
|
|
|
|
}
|
|
|
|
i++;
|
|
|
|
}
|
|
|
|
ft_freer_tab_ultimate(1, tab);
|
|
|
|
}
|
|
|
|
return (path);
|
|
|
|
}
|
2023-02-09 12:47:05 -05:00
|
|
|
|
2023-02-14 07:38:40 -05:00
|
|
|
static int ft_excutor(t_cmd *cmd, char **env)
|
2023-02-09 12:47:05 -05:00
|
|
|
{
|
|
|
|
int pid;
|
2023-02-14 07:38:40 -05:00
|
|
|
char *executable;
|
|
|
|
int return_value;
|
2023-02-09 12:47:05 -05:00
|
|
|
|
|
|
|
pid = fork();
|
|
|
|
if (pid == -1)
|
|
|
|
return (1);
|
|
|
|
if (pid == 0)
|
|
|
|
{
|
2023-02-14 01:21:24 -05:00
|
|
|
dup2(cmd->fd_out, 1);
|
|
|
|
dup2(cmd->fd_in, 0);
|
2023-02-14 07:38:40 -05:00
|
|
|
execve(executable, cmd->args, env);
|
2023-02-09 12:47:05 -05:00
|
|
|
}
|
|
|
|
else
|
2023-02-14 07:38:40 -05:00
|
|
|
waitpid(pid, &return_value, 0);
|
|
|
|
return (return_value);
|
|
|
|
}
|
|
|
|
|
|
|
|
int ft_cmds_executor(t_list **cmds, char **env)
|
|
|
|
{
|
|
|
|
t_cmd *content;
|
|
|
|
t_list *current;
|
|
|
|
int fds[2];
|
|
|
|
|
|
|
|
current = *cmds;
|
|
|
|
while (current->next != NULL)
|
|
|
|
{
|
|
|
|
if (pipe(fds) == -1)
|
|
|
|
{
|
|
|
|
ft_eprintf("minishell: pipe failed");
|
|
|
|
return (1);
|
|
|
|
}
|
|
|
|
content->fd_out = fds[1];
|
|
|
|
((t_cmd *) current->next)->fd_in = fds[0];
|
|
|
|
ft_excutor(content, env);
|
|
|
|
current = current->next;
|
|
|
|
}
|
|
|
|
return (0);
|
2023-02-09 12:47:05 -05:00
|
|
|
}
|