-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_heredoc.c
executable file
·107 lines (96 loc) · 2.41 KB
/
ft_heredoc.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_heredoc.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abenheni <abenheni@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/04/17 02:20:07 by mazaroua #+# #+# */
/* Updated: 2023/09/30 13:49:25 by abenheni ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
int count_heredocs(t_cmd_line **cmd_line)
{
t_redirections *redirections;
int count;
redirections = (*cmd_line)->redirections;
count = 0;
while (redirections)
{
if (redirections->type == HEREDOC)
count++;
redirections = redirections->next;
}
return (count);
}
char **get_delimiters(t_cmd_line **cmd_line)
{
t_redirections *curr;
char **delimiters;
int i;
curr = (*cmd_line)->redirections;
delimiters = (char **)ft_malloc(sizeof(char *),
(count_heredocs(cmd_line) + 1));
i = 0;
while (curr)
{
if (curr->type == HEREDOC)
delimiters[i++] = curr->file;
curr = curr->next;
}
delimiters[i] = NULL;
return (delimiters);
}
void heredoc_prompt(char *delimiter, int fd)
{
char *buffer;
while (1337)
{
// buffer = readline("> ");
if (!buffer)
{
g_var.lastchance = 1;
break ;
}
if (!(ft_strcmp(buffer, delimiter)))
{
free(buffer);
break ;
}
buffer = ft_strjoin_heredoc(buffer, "\n");
write (fd, buffer, ft_strlen(buffer));
}
}
void recover_stdin(void)
{
int tty_fd;
if (!ttyname(0))
{
tty_fd = open(ttyname(STDOUT_FILENO), O_RDONLY);
dup2(tty_fd, 0);
write(1, "\n", 1);
}
}
int ft_heredoc(t_cmd_line **cmd_line)
{
int i;
int fd[2];
char **delimiters;
i = 0;
delimiters = get_delimiters(cmd_line);
if (count_heredocs(cmd_line) == 0)
return (0);
g_var.heredoc = 1;
while (i < count_heredocs(cmd_line))
{
pipe(fd);
if (g_var.heredoc == -1)
break ;
heredoc_prompt(delimiters[i], fd[1]);
close(fd[1]);
i++;
}
recover_stdin();
return (fd[0]);
}