-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
95 lines (86 loc) · 2.34 KB
/
main.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ahaifoul <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/12/12 14:35:43 by ahaifoul #+# #+# */
/* Updated: 2021/12/20 10:38:01 by ahaifoul ### ########.fr */
/* */
/* ************************************************************************** */
#include "pipex.h"
void child1_pro(int *fd, int f1, char **av, char **envp)
{
close (fd[0]);
dup2(f1, STDINPUT_FILE);
dup2(fd[1], STDOUT_FILE);
close (f1);
pars_exec_cmd1(av, envp);
}
void child2_pro(int *fd, int f2, char **av, char **envp)
{
close (fd[1]);
dup2(fd[0], STDINPUT_FILE);
dup2(f2, STDOUT_FILE);
close (f2);
pars_exec_cmd2(av, envp);
}
int check_access(char *av, char **envp)
{
char **spltd_paths;
char **cmd_options;
char *access_par;
int i;
int ret;
cmd_options = ft_split(av, ' ');
spltd_paths = spltd(envp);
i = 0;
while (spltd_paths[i++])
{
access_par = ft_strjoin(spltd_paths[i], cmd_options[0]);
ret = access(access_par, X_OK);
if (ret == 0)
return (0);
}
return (1);
}
void pipex(int f1, int f2, char **av, char **envp)
{
int fd[2];
int pid;
int pid1;
pipe(fd);
if (check_access(av[2], envp) || check_access(av[3], envp))
return (perror("command not found: "));
pid = fork();
if (pid == -1)
return (perror("Fork: "));
if (pid == 0)
child1_pro(fd, f1, av, envp);
pid1 = fork();
if (pid1 == -1)
return (perror("Fork: "));
if (pid1 == 0)
child2_pro(fd, f2, av, envp);
close (fd[0]);
close (fd[1]);
waitpid (pid, NULL, 0);
waitpid (pid1, NULL, 0);
}
int main(int ac, char **av, char **envp)
{
int f1;
int f2;
if (ac > 2)
{
f1 = open(av[1], O_RDONLY);
f2 = open(av[4], O_CREAT | O_RDWR | O_TRUNC, 0644);
if (f1 < 0 || f2 < 0)
return (0);
pipex(f1, f2, av, envp);
return (0);
}
else
return (-1);
}