maxishell
Implementation of a shell for Linux-like systems
Loading...
Searching...
No Matches
pipe.c
Go to the documentation of this file.
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* pipe.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: dmdemirk <dmdemirk@student.42london.c +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2024/06/17 11:04:39 by dmdemirk #+# #+# */
9/* Updated: 2024/06/26 14:47:46 by dmdemirk ### ########.fr */
10/* */
11/* ************************************************************************** */
12
13#include "shell.h"
14#include <unistd.h>
15#include "libft.h"
16#include "execute.h"
17#include <stdio.h>
18#include <sys/wait.h>
19#include "pipe.h"
20
21int builtin_pipe(t_ast *node, t_ms_data *data);
22pid_t execute_child(t_ast *node, t_ms_data *data, \
23 int fd[2], int direction);
24
35int builtin_pipe(t_ast *node, t_ms_data *data)
36{
37 int fd[2];
38 pid_t pid_1;
39 pid_t pid_2;
40 int status;
41
42 pid_2 = -1;
43 if (pipe(fd) == -1)
44 ft_perror("pipe");
45 pid_1 = execute_child(node->left, data, fd, 0);
46 if (node->right != NULL)
47 pid_2 = execute_child(node->right, data, fd, 1);
48 else
49 {
50 close(fd[1]);
51 data->std_in = fd[0];
52 return (WAIT_NEXT_COMMAND);
53 }
54 close_fds(fd[0], fd[1]);
55 if (pid_1 > 0)
56 waitpid(pid_1, &status, 0);
57 if (node->right != NULL && pid_2 > 0)
58 waitpid(pid_2, &status, 0);
59 return (WEXITSTATUS(status));
60}
61
71pid_t execute_child(t_ast *node, t_ms_data *data, \
72 int fd[2], int direction)
73{
74 pid_t pid;
75
76 pid = fork();
77 if (pid == -1)
78 ft_perror("fork");
79 if (pid == 0)
80 {
81 if (direction == 0)
82 dup2(fd[1], STDOUT_FILENO);
83 else
84 dup2(fd[0], STDIN_FILENO);
85 close_fds(fd[0], fd[1]);
86 execute_ast(node, data);
87 exit(EXIT_SUCCESS);
88 }
89 return (pid);
90}
int execute_ast(t_ast *node, t_ms_data *data)
execute Abstract Syntax Tree
Definition execute.c:38
void close_fds(int in, int out)
close two file descriptors
Definition utils_0.c:28
int ft_perror(char *str)
#define EXIT_SUCCESS
Definition exit_status.h:16
pid_t execute_child(t_ast *node, t_ms_data *data, int fd[2], int direction)
execute child process in the pipe context
Definition pipe.c:71
int builtin_pipe(t_ast *node, t_ms_data *data)
execute pipe when | is found in the command
Definition pipe.c:35
#define WAIT_NEXT_COMMAND
Definition pipe.h:19
Definition tokens.h:50
struct s_ast * right
Definition tokens.h:54
struct s_ast * left
Definition tokens.h:53
int std_in
Definition shell.h:26