/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* caller.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: narnaud +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/02/16 16:46:53 by narnaud #+# #+# */ /* Updated: 2022/03/24 17:15:24 by narnaud ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" int command_call(char *argv[], int input_fd, int output_fd) { if (ft_strncmp(argv[0], "echo", 4) == 0) return (ft_echo(argv, output_fd)); else if (ft_strncmp(argv[0], "pwd", 3) == 0) return (ft_pwd(argv, input_fd, output_fd)); else if (ft_strncmp(argv[0], "cd", 2) == 0) return (ft_cd(argv, input_fd, output_fd)); else if (ft_strncmp(argv[0], "export", 6) == 0) return (ft_export(argv, input_fd, output_fd)); else if (ft_strncmp(argv[0], "unset", 5) == 0) return (ft_unset(argv, input_fd, output_fd)); else if (ft_strncmp(argv[0], "env", 3) == 0) return (ft_env(argv, input_fd, output_fd)); else if (ft_strncmp(argv[0], "exit", 4) == 0) return (close_minishell(0)); else { errno = EINVAL; return (-1); } } void exe(char *argv[], char *const envp[]) { char **path_dirs; char *path; size_t path_length; execve(argv[0], argv, envp); path_dirs = ft_split(getenv("PATH"), ':'); while (path_dirs) { path_length = ft_strlen(*path_dirs) + ft_strlen(argv[0]) + 2; path = ft_calloc(path_length, sizeof(char)); ft_memcpy(path, *path_dirs, ft_strlen(*path_dirs)); ft_memcpy(path + ft_strlen(*path_dirs),"/", 1); ft_memcpy(path + ft_strlen(*path_dirs) + 1, argv[0], ft_strlen(argv[0])); free(path); execve(path, argv, envp); path_dirs++; } } int caller(t_command *command, int input_fd, int output_fd) { pid_t pid; int cmd_ret; int status; if (command->input != 0) input_fd = command->fd[0]; if (command->output != 1) output_fd = command->fd[1]; else if (!command->next) output_fd = 1; cmd_ret = command_call(command->argv, input_fd, output_fd); if (cmd_ret == -1 && errno == EINVAL) { pid = fork(); termios(1); if (pid == 0) { if (command->prev || command->input || command->heredoc) { dup2(input_fd, STDIN_FILENO); close(input_fd); } if (command->next || command->output) dup2(output_fd, STDOUT_FILENO); exe(command->argv, command->envp); } //signal(SIGINT, NULL); //signal(SIGQUIT, NULL); waitpid(pid, &status, 0); //signal(SIGINT, sigs_handler); //signal(SIGQUIT, sigs_handler); termios(0); if (command->output) close(command->output); if (WIFSIGNALED(status)) return (-1); if (!WIFEXITED(status)) printf("Minishell: command not found: '%s'\n", command->argv[0]); } return (0); }