minishell/src/executing/simple_cmd/simple_cmd_execute.c

88 lines
2.5 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* simple_cmd_execute.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: khais <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/03/27 16:21:56 by khais #+# #+# */
/* Updated: 2025/03/31 16:20:46 by khais ### ########.fr */
/* */
/* ************************************************************************** */
#include "simple_cmd_execute.h"
#include "builtins.h"
#include "libft.h"
#include "../../subst/subst.h"
#include "../../env/env_convert.h"
#include <unistd.h>
#include <sys/wait.h>
static char **argv_from_wordlist(t_wordlist *wordlist)
{
char **out;
int i;
out = ft_calloc(wordlist_size(wordlist) + 1, sizeof(char *));
i = 0;
while (wordlist != NULL)
{
out[i++] = ft_strdup(wordlist->word->word);
wordlist = wordlist->next;
}
return (out);
}
static void command_not_found(t_simple_cmd *cmd)
{
ft_dprintf(STDERR_FILENO, "minishell: %s: command not found\n",
cmd->words->word->word);
}
static t_builtin_type get_builtin(t_simple_cmd *cmd)
{
char *word;
word = cmd->words->word->word;
if (ft_strcmp("pwd", word) == 0)
return (BUILTIN_PWD);
if (ft_strcmp("cd", word) == 0)
return (BUILTIN_CD);
return (BUILTIN_INVALID);
}
static t_builtin_type execute_builtin(t_simple_cmd *cmd, t_minishell *app)
{
t_builtin_type type;
static t_builtin_type (*builtins[])(t_simple_cmd *, t_minishell *) = {
[BUILTIN_INVALID] = builtin_invalid,
[BUILTIN_PWD] = builtin_pwd,
[BUILTIN_CD] = builtin_cd,
};
type = get_builtin(cmd);
return (builtins[type](cmd, app));
}
void simple_cmd_execute(t_simple_cmd *cmd, t_minishell *app)
{
char *exe;
int pid;
if (cmd == NULL || cmd->words == NULL || cmd->words->word == NULL)
return ;
if (execute_builtin(cmd, app) != BUILTIN_INVALID)
return ;
exe = get_cmdpath(cmd->words->word->word, app);
if (exe == NULL)
{
command_not_found(cmd);
return ;
}
pid = fork();
if (pid == 0)
execve(exe, argv_from_wordlist(cmd->words), envp_from_env(app->env));
free(exe);
waitpid(pid, NULL, 0);
return ;
}