42_minishell/heredoc.c

67 lines
1.6 KiB
C
Raw Normal View History

2023-02-17 10:33:52 -05:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* 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"
2023-02-03 10:02:52 -05:00
#include "minishell.h"
#include <stdlib.h>
2023-02-03 10:02:52 -05:00
2023-02-23 09:14:08 -05:00
int *ft_get_heredoc()
{
static int heredoc;
return (&heredoc);
}
int ft_heredoc_creator(char *stop, int fd)
2023-02-03 10:02:52 -05:00
{
char *line;
line = readline("> ");
while (line != NULL)
{
if (ft_strcmp(line, stop) == 0)
break ;
ft_putendl_fd(line, fd);
2023-02-03 10:02:52 -05:00
free(line);
line = readline("> ");
2023-02-23 09:14:08 -05:00
if (line == NULL)
return (1);
2023-02-03 10:02:52 -05:00
}
return (0);
2023-02-03 10:02:52 -05:00
}
2023-02-23 09:14:08 -05:00
int ft_heredoc(char *stop)
{
int pid;
int fds[2];
int exit_code;
2023-02-23 09:14:08 -05:00
if (pipe(fds) == -1)
return (-1);
2023-02-23 09:14:08 -05:00
pid = fork();
if (pid == -1)
return (-1);
if (pid == 0)
{
exit_code = ft_heredoc_creator(stop, fds[1]);
exit (exit_code + 1);
2023-02-23 09:14:08 -05:00
}
else
{
*ft_get_heredoc() = pid;
waitpid(pid, &exit_code, 0);
*ft_get_heredoc() = 0;
close(fds[1]);
return (fds[0]);
2023-02-23 09:14:08 -05:00
}
}