#include "libftx/libftx.h" #include "minishell.h" #include "utils/utils.h" #include static char *ft_get_executable_path(char *executable_name, t_list **env) { char *path; char *temp; char **tab; size_t i; path = NULL; if (executable_name[0] == '.' || executable_name[0] == '/') { path = ft_strdup(executable_name); if (path == NULL) { ft_eprintf("minishell: malloc failed\n"); return (NULL); } if (access(path, X_OK) == 0) { ft_eprintf("minishell: %s: permission denied\n", path); return (NULL); } } else { tab = ft_split(get_value_by_key("PATH", env), ':'); if (tab == NULL) return (NULL); i = 0; while (tab[i] != NULL) { temp = ft_strmerger(3, tab[i], "/", executable_name); if (temp == NULL) { ft_freer_tab_ultimate(1, tab); free(executable_name); ft_eprintf("minishell: malloc failed\n"); } if (access(temp, X_OK) == 0) { path = temp; break ; } free(temp); i++; } if (path == NULL) { ft_eprintf("%s: command not found\n", executable_name); } ft_freer_tab_ultimate(1, tab); } return (path); } static int ft_excutor(t_cmd *cmd, t_list **env) { int pid; int return_value; char **tab; if (cmd->fd_in == -1 || cmd->fd_out == -1) return (1); pid = fork(); if (pid == -1) return (1); if (pid == 0) { tab = env_to_strs(env); if (tab == NULL) return (1); tab = NULL; dup2(cmd->fd_out, 1); dup2(cmd->fd_in, 0); execve(cmd->executable, cmd->args, tab); } else waitpid(pid, &return_value, 0); return (return_value); } int ft_cmds_executor(t_list **cmds, t_list **env) { t_cmd *content; t_list *current; int fds[2]; current = *cmds; while (current != NULL) { content = current->content; if (current->next != NULL) { if (pipe(fds) == -1) { ft_eprintf("minishell: pipe failed\n"); return (1); } content->fd_out = fds[1]; ((t_cmd *) current->next->content)->fd_in = fds[0]; } content->executable = ft_get_executable_path(content->executable, env); if (content->executable != NULL) ft_excutor(content, env); close(content->fd_in); close(content->fd_out); current = current->next; } return (0); }