diff --git a/src/exec_command.c b/src/exec_command.c new file mode 100644 index 0000000..470e905 --- /dev/null +++ b/src/exec_command.c @@ -0,0 +1,62 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* exec_command.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: jschaft +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* 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); +} diff --git a/src/path.c b/src/path.c index 82b5a85..14b2e08 100644 --- a/src/path.c +++ b/src/path.c @@ -6,13 +6,13 @@ /* By: jschaft +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* 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); }