-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipex.c
78 lines (69 loc) · 2.38 KB
/
pipex.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/* ************************************************************************** */
/* */
/* :::::::: */
/* pipex.c :+: :+: */
/* +:+ */
/* By: rcappend <[email protected]> +#+ */
/* +#+ */
/* Created: 2021/09/20 13:00:22 by rcappend #+# #+# */
/* Updated: 2021/09/22 14:33:50 by rcappend ######## odam.nl */
/* */
/* ************************************************************************** */
#include "pipex.h"
static void execute_command(t_cmd cmd, char **envp)
{
char *full_cmd;
full_cmd = get_full_command(cmd, envp);
if (!full_cmd)
return (exit_error(8, "Command can't be found"));
if (execve(full_cmd, cmd.args, envp) == ERROR)
return (perror("Execve"));
exit_error(666, "Failure to execute command");
}
static void firstborn(int end[2], int fd_in, t_cmd cmd, char **envp)
{
if (dup2(fd_in, STDIN_FILENO) == ERROR)
return (perror("Dup2 #1"));
if (dup2(end[WRITE], STDOUT_FILENO) == ERROR)
return (perror("Dup2 #2"));
close(fd_in);
close(end[READ]);
execute_command(cmd, envp);
}
static void secondborn(int end[2], int fd_out, t_cmd cmd, char **envp)
{
if (dup2(end[READ], STDIN_FILENO) == ERROR)
return (perror("Dup2 #1"));
if (dup2(fd_out, STDOUT_FILENO) == ERROR)
return (perror("Dup2 #2"));
close(fd_out);
close(end[WRITE]);
execute_command(cmd, envp);
}
static void parent_process(int end[2], pid_t pid_1, pid_t pid_2)
{
int status;
close(end[READ]);
close(end[WRITE]);
waitpid(pid_1, &status, 0);
waitpid(pid_2, &status, 0);
}
void pipex(int fd_in, int fd_out, t_cmd cmd[2], char **envp)
{
int end[2];
pid_t pid_1;
pid_t pid_2;
if (pipe(end) == ERROR)
return (perror("Pipe"));
pid_1 = fork();
if (pid_1 == ERROR)
return (perror("Fork #1"));
else if (pid_1 == CHILD)
firstborn(end, fd_in, cmd[0], envp);
pid_2 = fork();
if (pid_2 == ERROR)
return (perror("Fork #2"));
else if (pid_2 == CHILD)
secondborn(end, fd_out, cmd[1], envp);
parent_process(end, pid_1, pid_2);
}