42_minishell/redirection/heredoc.c
Camille Chauvet 5d482fc65a fix: signal
2023-04-05 15:35:52 +00:00

96 lines
2.3 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* heredoc.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/17 15:36:26 by cchauvet #+# #+# */
/* Updated: 2023/04/05 14:58:01 by alouis-j ### ########.fr */
/* */
/* ************************************************************************** */
#include "./redirection_private.h"
int *ft_get_heredoc(void)
{
static int heredoc = -1;
return (&heredoc);
}
static int ft_format_and_write(t_data *data, const char *str, int fd)
{
char *line_clean;
line_clean = ft_env_filler(data, str);
if (line_clean == NULL)
return (1);
ft_putendl_fd(line_clean, fd);
free(line_clean);
return (0);
}
static int ft_heredoc2(t_data *data, char *stop, int fds[2])
{
char *line;
ft_printf("> ");
line = get_next_line(*ft_get_heredoc());
if (line == NULL)
{
if (*ft_get_heredoc() == -1)
{
ft_putchar_fd('\n', 1);
ft_closer(fds);
return (1);
}
else
{
ft_eprintf("minishell: warning: here-document at line 1 delimited by end-of-file (wanted `%s')\n", stop);
return (2);
}
}
line[ft_strlen(line) - 1] = '\0';
if (ft_strcmp(line, stop) == 0)
{
free(line);
return (2);
}
if (ft_format_and_write(data, line, fds[1]))
{
ft_closer(fds);
free(line);
return (1);
}
free(line);
return (0);
}
int ft_heredoc(t_data *data, char *stop)
{
int fds[2];
int return_code;
if (pipe(fds) == -1)
return (-1);
*ft_get_heredoc() = dup(0);
while (true)
{
return_code = ft_heredoc2(data, stop, fds);
if (return_code == 2)
break ;
else if (return_code == 1)
{
if (*ft_get_heredoc() > 2)
close(*ft_get_heredoc());
*ft_get_heredoc() = -1;
return (-2);
}
}
close(*ft_get_heredoc());
*ft_get_heredoc() = -1;
close(fds[1]);
return (fds[0]);
}