/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   subshell_wait.c                                    :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: lperrey <lperrey@student.42.fr>            +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2021/11/16 01:57:38 by lperrey           #+#    #+#             */
/*   Updated: 2021/11/27 10:43:46 by lperrey          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

static int	handle_wait_error(void);

void	wait_subshell(pid_t last_cmd_pid)
{
	int	wstatus;
	int	ret;

	wstatus = 0;
	if (last_cmd_pid > 0)
	{
		if (waitpid(last_cmd_pid, &wstatus, 0) == -1)
			perror("waitpid()");
		if (WIFEXITED(wstatus))
			set_last_exit_status(WEXITSTATUS(wstatus));
		if (WIFSIGNALED(wstatus))
		{
			write(STDIN_FILENO, "\n", 1);
			set_last_exit_status(EXIT_SIGNAL + WTERMSIG(wstatus));
		}
	}
	ret = 0;
	while (ret != -1)
	{
		ret = wait(&wstatus);
		if (ret == -1)
			ret = handle_wait_error();
	}
}

static int	handle_wait_error(void)
{
	if (errno == ECHILD)
		return (-1);
	else if (errno == EINTR)
		return (0);
	else
		perror("wait()");
	return (-1);
}
