42_minishell/src/exec_command.c
2024-04-30 16:27:59 +02:00

71 lines
2 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* exec_command.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jschaft <cecile.schaft@orange.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/04/24 13:48:00 by jschaft #+# #+# */
/* Updated: 2024/04/30 13:58:04 by mcolonna ### ########.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);
}
static void fork_exec(const char *path, t_call call, const int inout[2],
char *const envp[])
{
dup2(inout[0], 0);
dup2(inout[1], 1);
execve(path, call.argv, envp);
}
static int execute_call(t_memclass mc, t_call call, const int inout[2],
char *const envp[])
{
char **const path = get_path(envp);
pid_t pid;
const char *program_path;
program_path = search_path(mc, (const char **)path, call.program);
if (!program_path)
return (127);
pid = fork();
if (pid < 0)
return (1);
if (pid == 0)
fork_exec(program_path, call, inout, envp);
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[])
{
const int inout[] = {command.input_fd, command.output_fd};
int nb_calls;
int r;
nb_calls = 1;
r = execute_call(mc, command.calls[0], inout, envp);
while (nb_calls)
{
wait(NULL);
nb_calls--;
}
return (r);
}