/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   subshell_exec.c                                    :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: lperrey <lperrey@student.42.fr>            +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2021/11/16 01:57:38 by lperrey           #+#    #+#             */
/*   Updated: 2021/11/29 12:43:55 by lperrey          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

int	cmd_exec_in_subshell(t_cmd *cmd, t_all *c)
{
	cmd->pid = fork();
	if (cmd->pid == -1)
		perror("fork()");
	if (cmd->pid == 0)
	{
		c->signal_behaviour.sa_handler = SIG_DFL;
		sigaction(SIGINT, &c->signal_behaviour, NULL);
		if (cmd->fd_in != STDIN_FILENO)
			if (dup2(cmd->fd_in, STDIN_FILENO) == -1)
				return (ft_reti_perror(EXIT_FAILURE, "dup2()"));
		if (cmd->fd_out != STDOUT_FILENO)
			if (dup2(cmd->fd_out, STDOUT_FILENO) == -1)
				return (ft_reti_perror(EXIT_FAILURE, "dup2()"));
		close_pipeline_fd(c->pipeline);
		if (cmd->builtin_func)
			exit_free(c, cmd->builtin_func(ft_2d_arrlen(cmd->argv), cmd->argv, c));
		else if (execve(cmd->path, cmd->argv, environ) == -1)
			return (ft_reti_perror_io(EXIT_FAILURE, "execve() ", cmd->argv[0]));
	}
	return (EXIT_SUCCESS);
}
