[ADD] added fonction to execute command

This commit is contained in:
joris schaft 2024-04-24 14:24:09 +02:00
parent 24d8b38510
commit 7654aeb2d8
2 changed files with 79 additions and 3 deletions

62
src/exec_command.c Normal file
View file

@ -0,0 +1,62 @@
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* exec_command.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jschaft <cecile.schaft@orange.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/04/24 13:48:00 by jschaft #+# #+# */
/* Updated: 2024/04/24 14:22:13 by jschaft ### ########.fr */
/* */
/* ************************************************************************** */
#include "include.h"
static void free_tab(char **tab)
{
int i;
i = 0;
while (tab[i] != NULL)
{
free(tab[i]);
i++;
}
free(tab[i]);
free(tab);
}
static void fork_exec(const char *path, t_command command, const char **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->argv, envp);
}
int execute_command(t_command command, const char **envp)
{
char **path;
pid_t pid;
int i;
i = 0;
path = get_path(envp);
while (path[i] != NULL)
{
path[i] = ft_strjoin(path[i], "/");
path[i] = ft_strjoin(path[i], command.calls->program);
i++;
}
i = search_path(path);
if (i == -1)
return (127);
pid = fork();
if (pid < 0)
return (1);
if (pid == 0)
fork_exec((const char *)path[i], command, envp);
free_tab(path);
return (0);
}

View file

@ -6,13 +6,13 @@
/* By: jschaft <cecile.schaft@orange.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/16 12:07:26 by jschaft #+# #+# */
/* Updated: 2024/04/24 13:26:41 by mcolonna ### ########.fr */
/* Updated: 2024/04/24 14:08:11 by jschaft ### ########.fr */
/* */
/* ************************************************************************** */
#include "include.h"
const char **get_path(const char **envp)
char **get_path(const char **envp)
{
int i;
char **re;
@ -24,5 +24,19 @@ const char **get_path(const char **envp)
path = ft_substr(envp[i], 5, ft_strlen(envp[i]) - 5);
re = ft_split(path, ':');
free(path);
return ((const char **)re);
return (char **re);
}
int search_path(char **path)
{
int i;
i = 0;
while (path[i] != NULL)
{
if (access(path[i], X_OK) >= 0)
return (i);
i++;
}
return (-1);
}