-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipex_process.c
89 lines (80 loc) · 2.31 KB
/
pipex_process.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* pipex_process.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yichoi <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/06/06 20:21:33 by yichoi #+# #+# */
/* Updated: 2022/06/13 22:24:09 by yichoi ### ########.fr */
/* */
/* ************************************************************************** */
#include "pipex.h"
void cmd1_process(int fd[2], char *argv[], char **envp)
{
int infile;
infile = open(argv[1], O_RDONLY, 0777);
if (infile == -1)
ft_error(ERR);
if (dup2(infile, STDIN_FILENO) == -1)
ft_error(ERR);
if (dup2(fd[1], STDOUT_FILENO) == -1)
ft_error(ERR);
close(fd[0]);
close(infile);
close(fd[1]);
execvision(argv[2], envp);
}
void cmd2_process(int fd[2], char *argv[], char **envp)
{
int outfile;
outfile = open(argv[4], O_WRONLY | O_CREAT | O_TRUNC, 0777);
if (outfile == -1)
ft_error(ERR);
if (dup2(fd[0], STDIN_FILENO) == -1)
ft_error(ERR);
if (dup2(outfile, STDOUT_FILENO) == -1)
ft_error(ERR);
close(fd[0]);
close(outfile);
close(fd[1]);
execvision(argv[3], envp);
}
void execvision(char *argv, char **envp)
{
char **cmd;
char *program_path;
cmd = ft_split(argv, ' ');
if (!cmd)
ft_error(ERR);
program_path = search_path(cmd[0], envp);
if (execve(program_path, cmd, envp) == -1)
ft_error(ERR);
}
char *search_path(char *cmd, char **envp)
{
char **other_paths;
char *path;
char *cmd_path;
int i;
i = -1;
path = ft_strjoin("/", cmd);
if (!path)
ft_error(ERR);
while (!ft_strnstr(envp[++i], "PATH", 4))
;
other_paths = ft_split(envp[i] + 5, ':');
if (!other_paths)
ft_error(ERR);
i = -1;
while (other_paths[++i])
{
cmd_path = ft_strjoin(other_paths[i], path);
if (!access(cmd_path, X_OK))
break ;
free(cmd_path);
}
str_isfree(other_paths);
free(path);
return (cmd_path);
}