summaryrefslogtreecommitdiffstats
path: root/src/e_redirs.c
blob: 246f2c75e4bea44c5602527d4d5740a2bfeb4afe (plain)
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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   e_redirs.c                                         :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: rbousset <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/02/14 17:19:27 by rbousset          #+#    #+#             */
/*   Updated: 2020/02/14 17:19:29 by rbousset         ###   ########lyon.fr   */
/*                                                                            */
/* ************************************************************************** */

#include <libft.h>
#include <stdint.h>
#include <stddef.h>
#include <fcntl.h>
#include <unistd.h>

#include "f_fail.h"
#include "s_destroy.h"
#include "s_line.h"
#include "s_struct.h"

static void	e_redir_minus_two(struct s_lredir *ptr)
{
	int32_t	fd[2];

	if (ptr->heredoc == NULL)
	{
		return ;
	}
	pipe(fd);
	dup2(fd[0], STDIN_FILENO);
	ft_dprintf(fd[1], "%s", ptr->heredoc);
	close(fd[1]);
	close(fd[0]);
}

static void	e_redir_minus_one(struct s_lredir *ptr, t_msh *msh)
{
	int32_t	fd;

	if ((fd = open(ptr->path, O_RDONLY)) == -1)
	{
		f_redir(ptr->path, msh);
		return ;
	}
	dup2(fd, STDIN_FILENO);
	close(fd);
}

static void	e_redir_plus_one(struct s_lredir *ptr, t_msh *msh)
{
	int32_t	fd;

	if ((fd = open(ptr->path, O_CREAT | O_TRUNC | O_WRONLY, 0644)) == -1)
	{
		f_redir(ptr->path, msh);
		return ;
	}
	dup2(fd, ptr->fd);
	close(fd);
}

static void	e_redir_plus_two(struct s_lredir *ptr, t_msh *msh)
{
	int32_t	fd;

	if ((fd = open(ptr->path, O_CREAT | O_APPEND | O_WRONLY, 0644)) == -1)
	{
		f_redir(ptr->path, msh);
		return ;
	}
	dup2(fd, ptr->fd);
	close(fd);
}

void		e_dup_redirs(const t_com *com, t_msh *msh)
{
	struct s_lredir	*ptr;

	ptr = com->rdr;
	while (ptr != NULL)
	{
		if (ptr->redir == -2 || ptr->redir == -3)
		{
			e_redir_minus_two(ptr);
		}
		else if (ptr->redir == -1)
		{
			e_redir_minus_one(ptr, msh);
		}
		else if (ptr->redir == 1)
		{
			e_redir_plus_one(ptr, msh);
		}
		else if (ptr->redir == 2)
		{
			e_redir_plus_two(ptr, msh);
		}
		ptr = ptr->next;
	}
}