aboutsummaryrefslogtreecommitdiff
path: root/src/interpreter.c
blob: 979a3cfc69bb31359efe06c62347b71d090eabf8 (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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   interpreter.c                                      :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: chuhlig <chuhlig@student.42.fr>            +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2024/12/17 19:15:49 by chuhlig           #+#    #+#             */
/*   Updated: 2025/01/22 15:20:18 by chuhlig          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "debug_tools.h"
#include "minishell.h"

int	eval_rec(t_node *node, t_env **env, int in_fd);

int	open_file(char *path, int flags, int mode)
{
	int	fd;

	fd = open(path, flags, mode);
	if (fd < 0)
		perror(path);
	return (fd);
}

int	eval_rec(t_node *node, t_env **env, int in_fd)
{
	int		p[2];
	pid_t	pid;
	int		result;

	if (node->type == PIPE_NODE)
	{
		if (pipe(p) == -1)
			return (perror("pipe"), EXIT_FAILURE);
		pid = fork();
		if (pid == -1)
			return (perror("fork"), close(p[0]), close(p[1]), EXIT_FAILURE);
		if (pid == 0)
			handle_pipe_child(p, node, env, in_fd);
		result = handle_pipe_parent(p, node, env);
	}
	else if (node->type == CMD_NODE)
		result = execute_cmd(&node->content.cmd, env);
	else
	{
		result = EXIT_FAILURE;
		free_node(node);
	}
	return (result);
}

int	eval(t_node *node, t_env **env)
{
	return (eval_rec(node, env, STDIN_FILENO));
}