-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipex.c
75 lines (68 loc) · 1.85 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* pipex.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mouaammo <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/12/14 17:49:44 by mouaammo #+# #+# */
/* Updated: 2022/12/21 14:17:15 by mouaammo ### ########.fr */
/* */
/* ************************************************************************** */
#include "pipex.h"
void usage(void)
{
ft_putstr_fd("\n\033[31mBab arguments\033[0m\n", 2);
ft_putstr_fd("Usage: ./pipex infile <cmd1> <cmd2> outfile\n\n", 2);
exit(EXIT_FAILURE);
}
void process(int i, char **av, char **env, int *fd)
{
int pid;
if (pipe(fd) == -1)
error();
pid = fork();
if (pid == -1)
error();
if (pid == 0)
{
dup2(fd[1], 1);
execute(env, av[i], fd);
}
dup2(fd[0], 0);
close(fd[1]);
wait(NULL);
}
void pipex(int ac, char **av, char **env)
{
int i;
int fd[2];
int out_fd;
int in_file;
i = 2;
in_file = open(av[1], O_RDONLY, 0777);
out_fd = open(av[ac - 1], O_RDWR | O_CREAT | O_TRUNC, 0777);
if (out_fd == -1)
error();
dup2(in_file, 0);
if (in_file == -1)
{
perror("");
i = ac -2;
dup2(out_fd, 0);
}
close(in_file);
while (i < ac - 2)
process(i++, av, env, fd);
dup2(out_fd, 1);
close(out_fd);
execute(env, av[ac - 2], fd);
}
int main(int ac, char **av, char **env)
{
if (ac == 5)
pipex(ac, av, env);
else
usage();
return (0);
}