Implement pipe duping
authorLukas Jiriste <ljiriste@student.42prague.com>
Thu, 1 Aug 2024 12:34:30 +0000 (14:34 +0200)
committerLukas Jiriste <ljiriste@student.42prague.com>
Thu, 1 Aug 2024 12:34:30 +0000 (14:34 +0200)
The order of closing the ends of pipes in ex_pipeline is done because
the reading end does not receive the eof unless the writting end is
closed. That means all file descriptors pointing to the writting end
have to be closed.
If the minishell itself only closes it after execution of the second
part of a pipe, it gets deadlocked, because minishell waits for the
process end to close the pipe and the process waits for the pipe to be
closed to exit.

src/execution.c

index 428d66a61e42204799bf72a8c656f098c3b1ed6d..72be3b30ce1b60941649e3a179c9029cb2ef52c7 100644 (file)
@@ -6,7 +6,7 @@
 /*   By: ljiriste <ljiriste@student.42prague.com>   +#+  +:+       +#+        */
 /*                                                +#+#+#+#+#+   +#+           */
 /*   Created: 2024/07/21 08:57:54 by ljiriste          #+#    #+#             */
-/*   Updated: 2024/08/01 13:46:06 by ljiriste         ###   ########.fr       */
+/*   Updated: 2024/08/01 14:28:28 by ljiriste         ###   ########.fr       */
 /*                                                                            */
 /* ************************************************************************** */
 
@@ -660,8 +660,12 @@ char       *find_exe(const char *exe_name, const t_execution_env *env)
        return (res);
 }
 
-int    dup_pipes(__attribute__((unused)) const t_execution_env *env)
+int    dup_pipes(const t_execution_env *env)
 {
+       if (dup2(env->stdin_fd, STDIN_FILENO) == -1)
+               return (1);
+       if (dup2(env->stdout_fd, STDOUT_FILENO) == -1)
+               return (1);
        return (0);
 }
 
@@ -838,11 +842,11 @@ int       ex_pipeline(t_parse_tree_node *pipeline, t_execution_env *env)
                ft_swap_int(&pipe_fds[1], &env->stdout_fd);
                ex_pipeline(ft_vec_access(&pipeline->children, 0), env);
                ft_swap_int(&pipe_fds[1], &env->stdout_fd);
+               close(pipe_fds[1]);
                ft_swap_int(&pipe_fds[0], &env->stdin_fd);
                ex_command(ft_vec_access(&pipeline->children, 2), env);
                ft_swap_int(&pipe_fds[0], &env->stdin_fd);
                close(pipe_fds[0]);
-               close(pipe_fds[1]);
        }
        return (0);
 }