-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuiltin.c
More file actions
90 lines (81 loc) · 1.93 KB
/
builtin.c
File metadata and controls
90 lines (81 loc) · 1.93 KB
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
#include "main.h"
/**
* cmp_builtins - Compare the command with a list of builtins.
* @comm: The command to compare.
*
* Return: 1 if the command is a builtin, 0 otherwise.
*/
int cmp_builtins(char *comm)
{
int i;
char *builtins_str[] = {"exit", "env", "setenv", "cd", NULL};
for (i = 0; builtins_str[i]; i++)
{
if (_strcmp(comm, builtins_str[i]) == 0)
return (1);
}
return (0);
}
/**
* handle_builtins - Handle the execution of builtins.
* @comm: The command to handle.
* @argv: List of argv. Not examined.
* @stats: Pointer to the shell status.
* @index: The index of the command.
*/
void handle_builtins(char **comm, char **argv, int *stats, int index)
{
(void)argv;
if (_strcmp(comm[0], "exit") == 0)
sh_exit(comm, argv, stats, index);
else if (_strcmp(comm[0], "env") == 0)
sh_env(comm, stats);
}
/**
* sh_exit - Handle the 'exit' builtin command.
* @comm: The command to handle.
* @argv: List of argv. Not examined.
* @stats: Pointer to the shell status.
* @index: The index of the command.
*/
void sh_exit(char **comm, char **argv, int *stats, int index)
{
char *idx, mssg[] = ": exit: Illegal number: ";
if (comm[1])
{
if (is_positive_nb(comm[1]))
*stats = _atoi(comm[1]);
else
{
idx = _itoa(index);
write(STDERR_FILENO, argv[0], _strlen(argv[0]));
write(STDERR_FILENO, ": ", 2);
write(STDERR_FILENO, idx, _strlen(idx));
write(STDERR_FILENO, mssg, _strlen(mssg));
write(STDERR_FILENO, comm[1], _strlen(comm[1]));
write(STDERR_FILENO, "\n", 1);
free(idx);
freed(comm);
(*stats) = 2;
return;
}
}
freed(comm);
exit(*stats);
}
/**
* sh_env - Handle the 'env' builtin command.
* @comm: The command to handle.
* @stats: Pointer to the shell status.
*/
void sh_env(char **comm, int *stats)
{
int i;
for (i = 0; environ[i] && _strlen(environ[i]); i++)
{
write(STDOUT_FILENO, environ[i], _strlen(environ[i]));
write(STDOUT_FILENO, "\n", 1);
}
freed(comm);
(*stats) = 0;
}