-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell2.c
More file actions
118 lines (108 loc) · 1.95 KB
/
shell2.c
File metadata and controls
118 lines (108 loc) · 1.95 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
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
116
117
118
#include "shell.h"
/**
* execute_commandV - Fork and execute the command.
* @m: The string that should be executed.
* Return: always 0.
*/
int execute_commandV(memory *m)
{
pid_t child_id = -1;
int command_status = 0;
m->agv = arr_of_tokens(m->command, " \t\r\n\a");
if (m->agv == NULL)
return (0);
handle_args(m), command_status = check_command_exit(m->agv);
if (command_status == -1)
{
fprintf(stderr, "%s: ", m->program_args[0]);
fprintf(stderr, "%d: %s: ", m->command_number, m->agv[0]);
fprintf(stderr, "not found\n"), free_array_of_strings(m->agv);
m->last_exit_code = 127;
return (-1);
}
if (command_status != 3)
{
child_id = fork();
if (child_id == 0)
{
execve(m->agv[0], m->agv, m->env);
if (errno == EACCES)
exit(126);
exit(1);
}
else
{
wait(&(m->current_status_code));
if (WIFEXITED(m->current_status_code))
{
m->current_status_code = WEXITSTATUS(m->current_status_code);
m->last_exit_code = m->current_status_code;
}
}
}
else
handle_built_in(m);
free_array_of_strings(m->agv);
return (0);
}
/**
* handle_built_in - handles the argguments.
* @m: the string.
*
* Return: description.
*/
int handle_built_in(memory *m)
{
int i = 0;
built_in h[] = {
{"exit", handle_exit},
{"cd", NULL},
{"env", handle_env},
{NULL, NULL}
};
while (h[i].command)
{
if (_strcmp(h[i].command, m->agv[0]) == 0)
{
h[i].handler(m);
return (1);
}
i++;
}
return (0);
}
/**
* handle_args - handles the argguments.
* @m: the string.
*
* Return: description.
*/
int handle_args(memory *m)
{
int i = 0;
int j = 0;
ArgsHandler h[] = {
{"#", handle_hash},
{"$$", handle_double_dollar},
{"$?", handle_double_mark},
{NULL, NULL}
};
while ((h + i)->name)
{
while (m->agv[j])
{
if (m->agv[j][0] == '#' && (h + i)->name[0] == '#')
{
(h + i)->handler(m, j);
}
else if (_strcmp((h + i)->name, m->agv[j]) == 0)
{
(h + i)->handler(m, j);
}
j++;
}
j = 0;
i++;
}
return (0);
}