57 lines
1.8 KiB
C
57 lines
1.8 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* exec_command.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: jschaft <cecile.schaft@orange.fr> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2024/04/24 13:48:00 by jschaft #+# #+# */
|
|
/* Updated: 2024/04/25 18:14:03 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);
|
|
}
|
|
|
|
// TODO works with only one call (no pipe).
|
|
// TODO is t_call.argv ended by NULL?
|
|
static void fork_exec(const char *path, t_command command, char *const envp[])
|
|
{
|
|
if (command.input_fd != 0)
|
|
dup2(command.input_fd, 0);
|
|
if (command.output_fd != 1)
|
|
dup2(command.output_fd, 1);
|
|
execve(path, command.calls[0].argv, envp);
|
|
}
|
|
|
|
// TODO works with only one call (no pipe).
|
|
int execute_command(t_memclass mc, t_command command, char *const envp[])
|
|
{
|
|
char **const path = get_path(envp);
|
|
pid_t pid;
|
|
const char* program_path;
|
|
|
|
program_path = search_path(mc, (const char **)path, command.calls[0].program);
|
|
if (!program_path)
|
|
return (127);
|
|
pid = fork();
|
|
if (pid < 0)
|
|
return (1);
|
|
if (pid == 0)
|
|
fork_exec(program_path, command, envp);
|
|
free_tab(path);
|
|
return (0);
|
|
}
|