89 lines
2.5 KiB
C
89 lines
2.5 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* builtin.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: jschaft <cecile.schaft@orange.fr> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2024/06/03 12:02:45 by jschaft #+# #+# */
|
|
/* Updated: 2024/06/25 13:37:36 by mcolonna ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "include.h"
|
|
|
|
// Check if str is the name of a builtin.
|
|
// Return true if it is, false if not.
|
|
bool is_builtin(const char *str)
|
|
{
|
|
return (
|
|
ft_strncmp(str, "cd", 3) == 0
|
|
|| ft_strncmp(str, "exit", 5) == 0
|
|
// || ft_strncmp(str, "export", 7) == 0
|
|
|| ft_strncmp(str, "env", 4) == 0
|
|
|| ft_strncmp(str, "pwd", 4) == 0
|
|
// || ft_strncmp(str, "echo", 5) == 0
|
|
// || ft_strncmp(str, "unset", 6) == 0
|
|
);
|
|
}
|
|
|
|
// Execute the builtin cd for the specified path.
|
|
// Return 0 if success, errno if error.
|
|
static int cd_builtin(const char *path)
|
|
{
|
|
int r;
|
|
|
|
r = chdir(path);
|
|
if (r)
|
|
{
|
|
perror("cd");
|
|
return (errno);
|
|
}
|
|
return (0);
|
|
}
|
|
|
|
//Execute the builtin pwd for the current directory.
|
|
// Return 0 for the sake of returning something for exec_builtin
|
|
static int pwd_builtin(void)
|
|
{
|
|
char *str;
|
|
|
|
str = getcwd(NULL, 0);
|
|
printf("%s\n", str);
|
|
free(str);
|
|
return (0);
|
|
}
|
|
|
|
static int env_builtin(char *const envp[])
|
|
{
|
|
int i;
|
|
|
|
i = 0;
|
|
while (envp[i] != NULL)
|
|
{
|
|
printf("%s\n", envp[i]);
|
|
i++;
|
|
}
|
|
return (0);
|
|
}
|
|
|
|
// Execute the specified builtin.
|
|
// The builtin must exist.
|
|
// Return the error value returned by the builtin.
|
|
// TODO all the builtins
|
|
int exec_builtin(t_call call, t_env *env)
|
|
{
|
|
if (ft_strncmp(call.program, "cd", 3) == 0)
|
|
return (cd_builtin(call.argv[1]));
|
|
if (ft_strncmp(call.program, "exit", 5) == 0)
|
|
env->exit = true;
|
|
/* if (ft_strncmp(call.program, "export", 7) == 0)
|
|
return (export_builtin(call.argv));
|
|
if (ft_strncmp(call.program, "unset", 6) == 0)
|
|
return (unset_builtin());*/
|
|
if (ft_strncmp(call.program, "pwd", 4) == 0)
|
|
return (pwd_builtin());
|
|
if (ft_strncmp(call.program, "env", 4) == 0)
|
|
return (env_builtin(env->envp));
|
|
return (1);
|
|
}
|