-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipex_utils.c
119 lines (110 loc) · 2.86 KB
/
pipex_utils.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/* ************************************************************************** */
/* */
/* :::::::: */
/* pipex_utils.c :+: :+: */
/* +:+ */
/* By: sramos <[email protected]> +#+ */
/* +#+ */
/* Created: 2024/05/22 12:48:58 by sramos #+# #+# */
/* Updated: 2024/08/22 10:38:55 by sramos ######## odam.nl */
/* */
/* ************************************************************************** */
#include "pipex.h"
char *find_path(char *cmd, char **paths, int i)
{
char *temp;
int j;
j = 1;
while (paths[i])
{
temp = ft_strjoin(paths[i], "/");
free(paths[i]);
paths[i] = ft_strjoin(temp, cmd);
free(temp);
if (access(paths[i], X_OK) == 0)
{
while (paths[i + j] != NULL)
{
free(paths[i + j]);
j++;
}
temp = paths[i];
free(paths);
return (temp);
}
free(paths[i]);
i++;
}
return (0);
}
char *check_envp(char **envp, char *cmd)
{
char **paths;
char *temp;
int i;
i = 0;
if (access(cmd, X_OK) == 0)
return (cmd);
while (ft_strnstr(envp[i], "PATH=", 5) == 0)
i++;
paths = ft_split(envp[i] + 5, ':');
if (!paths)
exit(1);
i = 0;
temp = find_path(cmd, paths, i);
if (temp)
return (temp);
free(paths);
return (0);
}
void execute(char **envp, char *argv)
{
char **cmd;
char *path;
int i;
i = 0;
cmd = ft_split(argv, ' ');
path = check_envp(envp, cmd[0]);
if (!path)
perror("Error on finding the comand.\n");
else if (execve(path, cmd, envp) == -1)
perror("Execve error!\n");
while (cmd[i])
{
free(cmd[i]);
i++;
}
free(cmd);
free(path);
exit (127);
}
void ft_error(int num)
{
if (num == 1)
perror("Error creating the pipe.\n");
else if (num == 2)
perror("Error on forking child 1.\n");
else if (num == 3)
perror("Error on waiting for child process ID!\n");
else if (num == 4)
perror("Error on forking child 2.\n");
else if (num == 5)
perror("Invalid input!\nCorrect input:'./pipex file1 cmd1 cmd2 file2'");
else if (num == 6)
perror("Error on open function (fdout).\n");
else if (num == 7)
perror("Error on dup2 (STD_OUT) child2_process.\n");
else if (num == 8)
perror("Error on dup2 (STD_IN) child2_process.\n");
exit(EXIT_FAILURE);
}
void ft_error_process_child1(int num)
{
if (num == 1)
perror("Error on open function (fdin).\n");
else if (num == 2)
perror("Error on dup2 (STD_IN) child1_process.\n");
else if (num == 3)
perror("Error on dup2 (STD_OUT) child1_process.\n");
exit(EXIT_SUCCESS);
}