-
Notifications
You must be signed in to change notification settings - Fork 1
/
builtins.c
105 lines (98 loc) · 1.86 KB
/
builtins.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
#include "shell_header.h"
/**
* check_builtins - checks for and executes builtins
* @arr: array containing command and arguments
* @path: linked list of the directories in the PATH env variable
* @buffer: full command line input
* @status: current execution status of the shell
*
* Return: 1 if a builtin completes, 0 if no builtin is found
*/
int check_builtins(char **arr, paths *path, char *buffer, int status)
{
if (_strcmp(arr[0], "exit") == 0)
{
exit_shell(path, arr, buffer, status);
write(1, "invalid exit value\n", 19);
return (1);
}
else if (_strcmp(arr[0], "env") == 0)
{
print_env();
return (1);
}
return (status);
}
/**
* exit_shell - exits the shell
* @arr: array containing command and arguments
* @path: linked list of the directories in the PATH env variable
* @buffer: full command line input
* @status: current execution status of the shell
*/
void exit_shell(paths *path, char **arr, char *buffer, int status)
{
if (arr[1] != NULL)
{
status = _atoi(arr[1]);
if (status < 0)
return;
}
if (path)
free_list(path);
free(arr);
free(buffer);
fflush(stdin);
exit(status);
}
/**
* print_env - prints the current enviroment
*/
void print_env(void)
{
int i;
for (i = 0; environ[i] != NULL; i++)
{
write(1, environ[i], _strlen(environ[i]));
write(1, "\n", 1);
}
}
/**
* _atoi - converts a string to an integer
* @s: input string
*
* Return: the converted integer
*/
int _atoi(char *s)
{
int i, l, n, sign;
n = 0;
sign = 1;
i = 0;
while (s[i] != '\0')
{
i++;
}
l = i;
for (i = 0; i < l; i++)
{
if (s[i] == '-')
sign *= -1;
else if (s[i] >= '0' && s[i] <= '9')
{
if ((n * -10) - (s[i] - 48) == -2147483648)
{
n = (n * -10) - (s[i] - 48);
return (n);
}
n = n * 10 + (s[i] - '0');
if (s[i + 1] < '0' || s[i + 1] > '9')
break;
}
else
{
return (-1);
}
}
return (n * sign);
}