aboutsummaryrefslogtreecommitdiff
path: root/src/interpreter.c
blob: f6757c422b64913e1f9f1e7959d7937c5b56ca17 (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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   interpreter.c                                      :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: dkaiser <dkaiser@student.42heilbronn.de    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2024/08/05 13:15:24 by dkaiser           #+#    #+#             */
/*   Updated: 2024/10/22 15:42:07 by dkaiser          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "debug_tools.h"
#include "minishell.h"
#include <stdlib.h>
#include <sys/_types/_pid_t.h>
#include <sys/cdefs.h>
#include <sys/wait.h>
#include <unistd.h>

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

int	eval(t_node *node, t_env *env)
{
	pid_t	pid;
	int		result;

	result = 0;
	pid = fork();
	if (pid < 0)
	{
		return (EXIT_FAILURE);
	}
	if (pid == 0)
	{
		result = eval_rec(node, env);
		exit(result);
	}
	else
	{
		waitpid(pid, &result, 0);
	}
	return (result);
}

int	eval_rec(t_node *node, t_env *env)
{
	pid_t	pid;
	int		result;

	if (node->type == PIPE_NODE)
	{
		pid = fork();
		if (pid < 0)
		{
			return (EXIT_FAILURE);
		}
		if (pid == 0)
		{
			result = execute_cmd(&node->content.pipe.left->content.cmd, env);
			exit(result);
		}
		else
		{
			result = eval(node->content.pipe.right, env);
		}
	}
	else if (node->type == CMD_NODE)
	{
		result = execute_cmd(&node->content.cmd, env);
	}
	else
	{
		panic(UNREACHABLE);
		return (EXIT_FAILURE);
	}
	return (result);
}