100 lines
2.5 KiB
C
100 lines
2.5 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* exec_command.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: jschaft <cecile.schaft@orange.fr> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2024/04/24 13:48:00 by jschaft #+# #+# */
|
|
/* Updated: 2024/05/13 10:17:48 by jschaft ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "include.h"
|
|
|
|
// Free every element of tab, then tab itself.
|
|
static void free_tab(char **tab)
|
|
{
|
|
int i;
|
|
|
|
i = 0;
|
|
while (tab[i] != NULL)
|
|
{
|
|
free(tab[i]);
|
|
i++;
|
|
}
|
|
free(tab);
|
|
}
|
|
|
|
// TODO is t_call.argv ended by NULL?
|
|
static void fork_exec(const char *path, t_call call, t_pipes in, t_pipes out,
|
|
char *const envp[])
|
|
{
|
|
if (in.i != 0)
|
|
dup2(in.pipe[1], 0);
|
|
else
|
|
dup2(in.inout, 0);
|
|
if (out.inout == 0)
|
|
dup2(out.pipe[0], 1);
|
|
else
|
|
dup2(out.inout, 1);
|
|
execve(path, call.argv, envp);
|
|
}
|
|
|
|
static int execute_call(t_memclass mc, t_command cmd, t_pipes in, t_pipes out,
|
|
char *const envp[])
|
|
{
|
|
char **const path = get_path(envp);
|
|
pid_t pid;
|
|
const char *program_path;
|
|
int status;
|
|
int i;
|
|
|
|
i = in.i;
|
|
program_path = search_path(mc, (const char **)path, cmd.calls[i].program);
|
|
if (i == 0)
|
|
in.inout = cmd.input_fd;
|
|
if (out.inout == -1)
|
|
out.inout = cmd.output_fd;
|
|
if (!program_path)
|
|
return (127);
|
|
pid = fork();
|
|
if (pid < 0)
|
|
return (1);
|
|
if (pid == 0)
|
|
fork_exec(program_path, cmd.calls[i], in, out, envp);
|
|
waitpid(pid, &status, 0);
|
|
free_tab(path);
|
|
return (0);
|
|
}
|
|
|
|
// TODO works with only one call (no pipe).
|
|
int execute_command(t_memclass mc, t_command command, char *const envp[])
|
|
{
|
|
t_pipes *pipes;
|
|
int i;
|
|
|
|
i = 0;
|
|
while (command.calls[i].program != NULL)
|
|
i++;
|
|
pipes = malloc(sizeof(t_pipes) * i + 1);
|
|
i = 0;
|
|
while (command.calls[i].program != NULL)
|
|
{
|
|
if (pipe(pipes[i].pipe) < 0)
|
|
return (exec_error());
|
|
pipes[i].inout = 0;
|
|
i++;
|
|
}
|
|
pipes[i].inout = -1;
|
|
i = 0;
|
|
while (command.calls[i].program != NULL)
|
|
{
|
|
pipes[i].i = i;
|
|
pipes[i + 1].i = i + 1;
|
|
execute_call(mc, command, pipes[i], pipes[i + 1], envp);
|
|
i++;
|
|
}
|
|
free(pipes);
|
|
return (0);
|
|
}
|