pipex/bonus/pipex_utils2.c
Etienne Rey-bethbeder 5006061fa6 Correction Pipex
2023-03-07 19:49:15 +01:00

89 lines
2.2 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* pipex_utils2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: erey-bet <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/14 15:46:08 by erey-bet #+# #+# */
/* Updated: 2023/03/07 18:56:52 by erey-bet ### ########.fr */
/* */
/* ************************************************************************** */
#include "pipex.h"
static int open_close_pipe(t_data *data, int boolean, int file)
{
if (!boolean)
{
if (!file)
if (pipe(data->fd[0]) < 0)
return (1);
if (file)
if (pipe(data->fd[1]) < 0)
return (1);
}
else
{
if (!file)
if (close(data->fd[0][0]) < 0 || close(data->fd[0][1]) < 0)
return (1);
if (file)
if (close(data->fd[1][0]) < 0 || close(data->fd[1][1]) < 0)
return (1);
}
return (0);
}
static void choice_command(int argc, t_data data, int i)
{
if (i == 0)
cmd(data, i, 0);
else if (i + 1 < argc - 3)
cmd(data, i, 1);
else
cmd(data, i, 2);
}
int pipex_loop(int argc, int **fk, t_data data)
{
int i;
i = -1;
while (++i < argc - 3)
{
if (open_close_pipe(&data, 0, i % 2))
return (1);
if ((i > 0 || (i == 0 && data.fd1 > 0)) && data.cmds[i])
{
(*fk)[i] = fork();
if ((*fk)[i] < 0)
return (1);
if ((*fk)[i] == 0)
choice_command(argc, data, i);
}
if (i > 0)
if (open_close_pipe(&data, 1, (i + 1) % 2))
return (1);
}
return (open_close_pipe(&data, 1, (i + 1) % 2));
}
int verification_command(char *argv[], t_data data)
{
int i;
i = -1;
while (++i < data.argc - 3)
{
data.cmds[i] = find_command(data.env, data.cmds[i]);
if (data.cmds[i] == NULL)
{
print_error(1, argv[2 + i]);
if (i == data.argc - 4)
return (free_all(&data));
}
}
return (0);
}