forked from mwanyambu/simple_shell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipe_builtin.c
62 lines (55 loc) · 957 Bytes
/
pipe_builtin.c
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
#include "main.h"
/**
* pipe_builtin - handles the pipe builtin
* @cmd1: first argument
* @cmd2: second argument
* Return: 1 else 0
*/
int pipe_builtin(char **cmd1, char **cmd2)
{
int _pipe[2], status;
pid_t pid1, pid2;
if (pipe(_pipe) != -1)
{
pid1 = fork();
if (pid1 == 0)
{
close(_pipe[0]);
dup2(_pipe[1], STDOUT_FILENO);
close(_pipe[1]);
execve(cmd1[0], cmd1, environ);
perror("execve");
_exit(EXIT_FAILURE);
}
else if (pid1 < 0)
{
perror("fork");
return (0);
}
pid2 = fork();
if (pid2 == 0)
{
close(_pipe[1]);
dup2(_pipe[0], STDIN_FILENO);
close(_pipe[0]);
execve(cmd2[0], cmd2, environ);
perror("execve");
_exit(EXIT_FAILURE);
}
else if (pid2 < 0)
{
perror("fork");
return (0);
}
close(_pipe[0]);
close(_pipe[1]);
waitpid(pid1, NULL, 0);
waitpid(pid2, &status, 0);
return (WEXITSTATUS(status) == 0);
}
else
{
perror("pipe");
return (0);
}
}