diff --git a/include/builtins.h b/include/builtins.h index dd75674..0bce9a3 100644 --- a/include/builtins.h +++ b/include/builtins.h @@ -6,33 +6,43 @@ /* By: sede-san builtins = ft_hashmap_new(4, ft_hashmap_hashstr, ft_hashmap_strcmp); + if (msh->builtins == NULL) + return (0); + ft_hashmap_put(msh->builtins, ft_strdup("cd"), builtin_cd); + ft_hashmap_put(msh->builtins, ft_strdup("echo"), builtin_echo); + ft_hashmap_put(msh->builtins, ft_strdup("exit"), builtin_exit); + ft_hashmap_put(msh->builtins, ft_strdup("pwd"), builtin_pwd); + return (1); +} + +u_int8_t is_builtin( + const char *command_name, + t_minishell *msh +) { + return (ft_hashmap_contains_key(msh->builtins, command_name)); +} diff --git a/src/builtins/echo/echo.c b/src/builtins/echo/echo.c index 1f110f5..5a8a729 100644 --- a/src/builtins/echo/echo.c +++ b/src/builtins/echo/echo.c @@ -6,7 +6,7 @@ /* By: sede-san exit = 1; // return the last exit_status, if none 0 is returned return (msh->exit_status); } @@ -37,7 +37,7 @@ u_int8_t builtin_exit( } else { - // msh.exit = 1; + msh->exit = 1; // cast to u_int8_t causes to return a value between 0 and 255 return ((u_int8_t)ft_atol(cmd.argv[1])); } diff --git a/src/executor/executor.c b/src/executor/executor.c index b054ee6..8e63767 100644 --- a/src/executor/executor.c +++ b/src/executor/executor.c @@ -6,38 +6,39 @@ /* By: sede-san exit_status = 127, msh->exit_status); } - if (access(cmd.path, X_OK) != EXIT_SUCCESS) + if (!is_builtin(cmd.path, msh) && access(cmd.path, X_OK) != EXIT_SUCCESS) { - // permission denied ft_eputstr("minishell: "); perror(cmd.path); return (msh->exit_status = 126, msh->exit_status); } - child_pid = fork(); + child_pid = 0; + if (!is_builtin(cmd.path, msh)) + child_pid = fork(); if (child_pid == -1) perror("minishell"); else if (child_pid == 0) @@ -55,7 +56,7 @@ static char *solve_path( char **path; size_t i; - if (path_is_solved(cmd_name)) + if (path_is_solved(cmd_name, msh)) // return a copy to avoid double free on parent return (ft_strdup(cmd_name)); path = ft_split(get_env("PATH", msh), COLON); @@ -88,11 +89,13 @@ static char *solve_path( } static u_int8_t path_is_solved( - char *cmd_name + char *cmd_name, + t_minishell *msh ){ return (ft_strncmp(cmd_name, "/", 1) == 0 || (cmd_name[1] && ft_strncmp(cmd_name, "./", 2) == 0) || (cmd_name[2] && ft_strncmp(cmd_name, "../", 3) == 0) + || is_builtin(cmd_name, msh) ); } @@ -100,11 +103,20 @@ static void handle_child( t_command *cmd, t_minishell *msh ){ - char **envp; + char **envp; + t_builtin_func builtin; - envp = get_envp(msh); - execve(cmd->path, cmd->argv, envp); - free_envp(envp); + if (is_builtin(cmd->argv[0], msh)) + { + builtin = ft_hashmap_get(msh->builtins, cmd->argv[0]); + builtin(*cmd, msh); + } + else + { + envp = get_envp(msh); + execve(cmd->path, cmd->argv, envp); + free_envp(envp); + } } static void handle_parent(