-
Notifications
You must be signed in to change notification settings - Fork 0
/
handle_built-in.c
115 lines (105 loc) · 2.14 KB
/
handle_built-in.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include "shell.h"
/**
* Isbuiltin - map the input command to the corresponding built-in function
*
* @command: the command to be mapped
*
* Return: On success returns a function pointer to the requested
* function. On failure returns NULL
*/
int (*Isbuiltin(char *command))(char **, char *, char **)
{
builtin_t my_builtin[] = {
{"exit", exit_cmd},
{"env", handle_env},
{NULL, NULL}
};
int i;
for (i = 0; my_builtin[i].cmd; i++)
{
if (_strcmp(command, my_builtin[i].cmd) == 0)
return (my_builtin[i].builtin_func);
}
return (NULL);
}
/**
* handle_env - handle built-in commands
*
* @tokens: Tokenized user input to be freed
* @lineptr: Raw user input to be freed
* @env: current environment
*
* Return: no return
*/
int handle_env(char **tokens, char *lineptr, char **env)
{
int i = 0;
(void) lineptr, (void) tokens, (void) env, (void) i;
while (env[i] != NULL)
{
_puts(env[i]);
i++;
}
return (1);
}
/**
* exit_cmd - handle exit command
*
* @tokens: Tokenized user input
* @lineptr: Raw user input to be freed
* @env: passed just because of the function pointer "Isbuiltin" prototype
*
* Return: exit status
*/
int exit_cmd(char **tokens, char *lineptr, char **env)
{
struct shell_info shell_exit;
(void) env;
if (tokens[1])
{
if (_isdigit(tokens[1]) == 0)
{
exit_error(tokens[1]);
_free(2, tokens, lineptr);
shell_exit.status = 2;
exit(shell_exit.status);
}
else
{
shell_exit.status = _atoi(tokens[1]);
if (shell_exit.status < 0)
{
_free(2, tokens, lineptr);
shell_exit.status = 2;
exit(shell_exit.status);
}
_free(2, tokens, lineptr);
exit(shell_exit.status);
}
}
_free(2, tokens, lineptr);
shell_exit.status = 0;
exit(shell_exit.status);
}
/**
* exit_error - check the passed argument to meet a certain criteria
*
* @arg: the argument passed
*
* Return: no return
*/
void exit_error(char *arg)
{
char *error = NULL;
error = malloc(_strlen(arg) + 40);
if (!error)
{
perror("malloc");
return;
}
_strcpy(error, "./hsh: 1: exit: Illegal number: ");
_strcat(error, arg);
_strcat(error, "\n");
write(STDERR_FILENO, error, _strlen(error));
free(error);
}