Files
42_INT_07_minishell/srcs/parser_hugo.c

76 lines
1.4 KiB
C

#include "minishell.h"
void **cmd_path(char **argv, char **envp)
{
int i;
char **path;
char *cmd;
i = 0;
while (envp[i] && ft_strncmp(envp[i], "PATH=", 5))
i++;
path = ft_split(envp[i] + 5, ':'); // 5 = lentgh of "PATH="
i = -1;
while (*path && i != 0)
{
cmd = ft_strjoin(path[0], "/");
cmd = ft_strjoin(cmd, argv[0]);
i = access(cmd, X_OK);
path++;
}
argv[0] = cmd;
return (NULL);
}
int handle_fd(char **input, int i, int fdin, int *fd_in, int *fd_out)
{
int *pipes_fd;
int next_in;
char *tmp;
*fd_in = fdin;
*fd_out = 1;
next_in = 0;
if (input[i + 1])
{
pipes_fd = calloc(2, sizeof(int));
pipe(pipes_fd);
*fd_out = pipes_fd[1];
next_in = pipes_fd[0];
}
tmp = ft_strchr(input[i], '>');
if (tmp)
{
tmp[0] = '\0';
tmp = ft_strtrim(tmp + 2, " "); // +2 for "> "
*fd_out = open(tmp, O_WRONLY | O_TRUNC);
next_in = *fd_out;
}
return (next_in);
}
t_list *parser(char *input, char **envp)
{
t_list *cmd;
t_cmd *element;
char **input_split;
int i;
int tmp_fd;
input_split = ft_split(input, '|');
tmp_fd = 0;
i = 0;
cmd = NULL;
while (input_split[i])
{
element = calloc(1, sizeof(t_cmd));
tmp_fd = handle_fd(input_split, i, tmp_fd, &(element->fd_in), &(element->fd_out));
element->argv = ft_split(input_split[i], ' ');
element->builtin = cmd_path(element->argv, envp);
ft_lstadd_back(&cmd, ft_lstnew(element));
i++;
}
return (cmd);
}