-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipex.c
94 lines (84 loc) · 2.64 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* pipex.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lrafael <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/06/21 09:01:45 by lrafael #+# #+# */
/* Updated: 2024/09/06 07:17:04 by lrafael ### ########.fr */
/* */
/* ************************************************************************** */
#include "./libft/libft.h"
static void ft_print_error(const char *msg)
{
ft_printf("%sError:%s %s\n", RED, RESET, msg);
exit(EXIT_FAILURE);
}
static void ft_execute(char *cmd[])
{
char *pathname;
pathname = ft_strjoin("/bin/", cmd[0]);
if (!pathname)
ft_print_error("path not found.");
if (execve(pathname, cmd, NULL) < 0)
ft_print_error("execve failed.");
}
static void ft_child_process(char **argv, int *fd)
{
int file_in;
char **arg;
file_in = open(argv[1], O_RDONLY, 0644);
if (file_in < 0)
ft_print_error("input file failed.");
if (dup2(fd[1], STDOUT_FILENO) < 0 || dup2(file_in, STDIN_FILENO) < 0)
ft_print_error("dup2 failed.");
arg = ft_split(argv[2], ' ');
if (!arg)
ft_print_error("command not found.");
close(file_in);
close(fd[0]);
close(fd[1]);
ft_execute(arg);
}
static void ft_parent_process(char **argv, int *fd)
{
int file_out;
char **arg;
file_out = open(argv[4], O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (file_out < 0)
ft_print_error("output file failed.");
if (dup2(fd[0], STDIN_FILENO) < 0 || dup2(file_out, STDOUT_FILENO) < 0)
ft_print_error("dup2 failed.");
arg = ft_split(argv[3], ' ');
if (!arg)
ft_print_error("command not found.");
close(file_out);
close(fd[0]);
close(fd[1]);
ft_execute(arg);
}
int main(int argc, char **argv)
{
int fd[2];
pid_t pid;
if (argc == 5 && argv[1][0] && argv[2][0] && argv[3][0] && argv[4][0])
{
if (pipe(fd) < 0)
ft_print_error("pipe failed.");
pid = fork();
if (pid < 0)
ft_print_error("fork failed.");
if (pid == 0)
ft_child_process(argv, fd);
waitpid(pid, NULL, 0);
ft_parent_process(argv, fd);
}
else
{
ft_printf("%s%sError:%s Bad arguments!\n", RED, BOLD, RESET);
ft_printf("%sEx: ./pipex <file1> <cmd1> <cmd2> <file2>\n%s", YELLOW,
RESET);
}
return (0);
}