111 lines
1.9 KiB
C
111 lines
1.9 KiB
C
#include "minishell.h"
|
|
|
|
void close_fd(t_cmd *cmd)
|
|
{
|
|
if (cmd->fd_in != 0)
|
|
close(cmd->fd_in);
|
|
if (cmd->fd_out != 1)
|
|
close(cmd->fd_out);
|
|
}
|
|
|
|
void exec_cmd(char **envp, t_list *cmd_list)
|
|
{
|
|
t_cmd *cmd;
|
|
pid_t pid;
|
|
pid_t wpid;
|
|
int status;
|
|
|
|
while(cmd_list)
|
|
{
|
|
cmd = cmd_list->content;
|
|
pid = fork();
|
|
if (pid == 0)
|
|
{
|
|
if (cmd->fd_in != 0)
|
|
dup2(cmd->fd_in, STDIN_FILENO);
|
|
if (cmd->fd_out != 1)
|
|
dup2(cmd->fd_out, STDOUT_FILENO);
|
|
close_fd(cmd);
|
|
execve(cmd->argv[0], cmd->argv, envp);
|
|
}
|
|
else
|
|
close_fd(cmd);
|
|
cmd_list = cmd_list->next;
|
|
}
|
|
// waitpid pour la derniere commande (pour '$?')
|
|
while ((wpid = wait(&status)) > 0);
|
|
}
|
|
|
|
int nbr_pipes(char *input)
|
|
{
|
|
int i;
|
|
int count;
|
|
|
|
i = -1;
|
|
count = 0;
|
|
while (input[++i])
|
|
if (input[i] == '|')
|
|
count++;
|
|
return (count);
|
|
}
|
|
|
|
int handle_fdd(char *input, int fdin, t_cmd *cmd)
|
|
{
|
|
int *pipes_fd;
|
|
int next_in;
|
|
char *tmp;
|
|
|
|
cmd->fd_in = fdin;
|
|
cmd->fd_out = 1;
|
|
next_in = 0;
|
|
if (input + 1)
|
|
{
|
|
pipes_fd = calloc(2, sizeof(int));
|
|
pipe(pipes_fd);
|
|
cmd->fd_out = pipes_fd[1];
|
|
next_in = pipes_fd[0];
|
|
}
|
|
tmp = ft_strchr(input, '>');
|
|
if (tmp)
|
|
{
|
|
tmp[0] = '\0';
|
|
tmp = ft_strtrim(tmp + 2, " "); // +2 for "> "
|
|
if (cmd->fd_out != 1)
|
|
close(cmd->fd_out);
|
|
cmd->fd_out = open(tmp, O_RDWR | O_TRUNC);
|
|
}
|
|
tmp = ft_strchr(input, '<');
|
|
if (tmp)
|
|
{
|
|
tmp[0] = '\0';
|
|
tmp = ft_strtrim(tmp + 2, " "); // +2 for "> "
|
|
if (cmd->fd_in != 0)
|
|
close(cmd->fd_in);
|
|
cmd->fd_in = open(tmp, O_RDONLY);
|
|
}
|
|
printf(" handle_fd: %s\n", input);
|
|
return (next_in);
|
|
}
|
|
|
|
t_cmd *fill_cmd(char *input, char **envp)
|
|
{
|
|
t_cmd *cmd;
|
|
char **input_split;
|
|
int i;
|
|
int tmp_fd;
|
|
|
|
cmd = calloc(nbr_pipes(input), sizeof(t_cmd));
|
|
input_split = ft_split(input, '|');
|
|
tmp_fd = 0;
|
|
i = 0;
|
|
while (input_split[i])
|
|
{
|
|
tmp_fd = handle_fdd(input_split[i], tmp_fd, &cmd[i]);
|
|
cmd[i].argv = ft_split(input_split[i], ' ');
|
|
cmd[i].builtin = cmd_path(cmd[i].argv, envp);
|
|
i++;
|
|
}
|
|
return (cmd);
|
|
}
|
|
|