42_minishell/heredoc.c
2023-02-23 18:03:22 +01:00

67 lines
1.6 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* heredoc.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/17 15:36:26 by cchauvet #+# #+# */
/* Updated: 2023/02/17 16:21:02 by cchauvet ### ########.fr */
/* */
/* ************************************************************************** */
#include "libftx/libftx.h"
#include "minishell.h"
#include <stdlib.h>
int *ft_get_heredoc()
{
static int heredoc;
return (&heredoc);
}
int ft_heredoc_creator(char *stop, int fd)
{
char *line;
line = readline("> ");
while (line != NULL)
{
if (ft_strcmp(line, stop) == 0)
break ;
ft_putendl_fd(line, fd);
free(line);
line = readline("> ");
if (line == NULL)
return (1);
}
return (0);
}
int ft_heredoc(char *stop)
{
int pid;
int fds[2];
int exit_code;
if (pipe(fds) == -1)
return (-1);
pid = fork();
if (pid == -1)
return (-1);
if (pid == 0)
{
exit_code = ft_heredoc_creator(stop, fds[1]);
exit (exit_code + 1);
}
else
{
*ft_get_heredoc() = pid;
waitpid(pid, &exit_code, 0);
*ft_get_heredoc() = 0;
close(fds[1]);
return (fds[0]);
}
}