minishell/src/utils/simple_builtins.c

111 lines
2.9 KiB
C

/* ************************************************************************** */
/* */
/* :::::::: */
/* simple_builtins.c :+: :+: */
/* +:+ */
/* By: whaffman <whaffman@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2025/02/05 16:21:39 by whaffman #+# #+# */
/* Updated: 2025/02/08 19:24:05 by willem ######## odam.nl */
/* */
/* ************************************************************************** */
#include "minishell.h"
void builtin_export(t_minishell *minishell)
{
t_list *tmp;
t_environment *env;
char **arr;
tmp = minishell->tokens->next;
while (tmp != NULL)
{
arr = ft_split(((t_token *)tmp->content)->value, '=');
if (arr[1] == NULL)
{
ft_free_arr(arr);
tmp = tmp->next;
continue ;
}
env = environment_get(minishell->environment, arr[0]);
if (env != NULL)
{
free(env->value);
env->value = ft_strdup(arr[1]);
}
else
environment_add(&(minishell->environment), arr[0], arr[1]);
ft_free_arr(arr);
tmp = tmp->next;
}
}
static int cmp_value(t_list *list, char *str)
{
if (list != NULL
&& ft_strncmp(
((t_token *)list->content)->value,
str,
ft_strlen(str) + 1) == 0)
return (TRUE);
return (FALSE);
}
void fork_execve(t_minishell *minishell, char *path, char **argv)
{
pid_t pid;
int status;
pid = fork();
if (pid == 0)
{
execve(path, argv, environment_get_arr(minishell->environment));
while (*argv != NULL)
printf("%s\n", *argv++);
printf("minishell->: %s: %s\n", path, strerror(errno));
exit(EXIT_FAILURE);
}
else if (pid < 0)
{
printf("minishell: %s\n", strerror(errno));
}
else
{
free(path);
waitpid(pid, &status, 0);
}
}
void simple_builtins(t_minishell *minishell)
{
char *path;
if (cmp_value(minishell->tokens, "clear"))
printf("\033[2J\033[1;1H");
else if (cmp_value(minishell->tokens, "env"))
environment_print(minishell->environment);
else if (cmp_value(minishell->tokens, "exit"))
{
free_minishell(minishell);
exit(EXIT_SUCCESS);
}
else if (cmp_value(minishell->tokens, "export"))
{
builtin_export(minishell);
}
else
{
path = executor_absolute_path(minishell->environment, ((t_token *)minishell->tokens->content)->value);
if (path == NULL)
printf("minishell: %s: command not found\n", ((t_token *)minishell->tokens->content)->value);
else
{
printf("found excutable: %s\n", path);
fork_execve(minishell, path, ft_split(((t_token *)minishell->tokens->content)->value, ' '));
}
}
}