-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexec.c
More file actions
93 lines (85 loc) · 2.45 KB
/
exec.c
File metadata and controls
93 lines (85 loc) · 2.45 KB
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* exec.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sanmetol <sanmetol@student.42madrid.com +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/11/26 20:27:44 by sanmetol #+# #+# */
/* Updated: 2024/11/26 22:27:03 by sanmetol ### ########.fr */
/* */
/* ************************************************************************** */
#include "pipex.h"
static char *get_cmd(char **paths, char *cmd)
{
char *tmp;
char *command;
while (*paths)
{
tmp = ft_strjoin(*paths, "/");
if (!tmp)
return (NULL);
command = ft_strjoin(tmp, cmd);
if (!command)
return (NULL);
if (access(command, 0) == 0)
return (command);
free(command);
command = NULL;
paths++;
}
return (NULL);
}
static int exec_cmd(t_pipex *pipex, char *command, char **envp)
{
char **cmd_args;
char *cmd_path;
cmd_args = ft_split(command, ' ');
if (!cmd_args)
handle_error('p', "Error splitting command", 1);
cmd_path = get_cmd(pipex->cmd_paths, cmd_args[0]);
if (!cmd_path)
{
free_cmd_args(cmd_args);
handle_error('p', "Command not found", 127);
}
if (execve(cmd_path, cmd_args, envp) == -1)
{
free_cmd_args(cmd_args);
handle_error('p', "Error executing command", 1);
}
return (0);
}
static void dup_and_exec(t_pipex *pipex, char *cmd, int cmd_index, char **envp)
{
if (cmd_index == 0)
dup2(pipex->infile, STDIN_FILENO);
else
dup2(pipex->pipes[cmd_index - 1][0], STDIN_FILENO);
if (cmd_index == pipex->cmd_count - 1)
dup2(pipex->outfile, STDOUT_FILENO);
else
dup2(pipex->pipes[cmd_index][1], STDOUT_FILENO);
close_pipes(pipex);
exec_cmd(pipex, cmd, envp);
handle_error('p', "Error executing cmd", 1);
}
int fork_and_exec(t_pipex *pipex, char **argv, char **envp)
{
int i;
int pid;
i = 0;
while (i < pipex->cmd_count)
{
pid = fork();
if (pid < 0)
{
perror("Error creating fork");
return (1);
}
if (pid == 0)
dup_and_exec(pipex, argv[i + 2 + pipex->here_doc], i, envp);
i++;
}
return (0);
}