-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
134 lines (121 loc) · 2.47 KB
/
main.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include "shell.h"
void sig_handler(int sig);
int execute(char **args, char **front);
/**
* sig_handler - Prints a new prompt upon a signal.
* @sig: The signal.
*/
void sig_handler(int sig)
{
char *new_prompt = "\n$ ";
(void)sig;
signal(SIGINT, sig_handler);
write(STDIN_FILENO, new_prompt, 3);
}
/**
* execute - Executes a command in a child process.
* @args: An array of arguments.
* @front: A double pointer to the beginning of args.
*
* Return: If an error occurs - a corresponding error code.
* O/w - The exit value of the last executed command.
*/
int execute(char **args, char **front)
{
pid_t child_pid;
int status, flag = 0, ret = 0;
char *command = args[0];
if (command[0] != '/' && command[0] != '.')
{
flag = 1;
command = get_location(command);
}
if (!command || (access(command, F_OK) == -1))
{
if (errno == EACCES)
ret = (create_error(args, 126));
else
ret = (create_error(args, 127));
}
else
{
child_pid = fork();
if (child_pid == -1)
{
if (flag)
free(command);
perror("Error child:");
return (1);
}
if (child_pid == 0)
{
execve(command, args, environ);
if (errno == EACCES)
ret = (create_error(args, 126));
free_env();
free_args(args, front);
free_alias_list(aliases);
_exit(ret);
}
else
{
wait(&status);
ret = WEXITSTATUS(status);
}
}
if (flag)
free(command);
return (ret);
}
/**
* main - Runs a simple UNIX command interpreter.
* @argc: The number of arguments supplied to the program.
* @argv: An array of pointers to the arguments.
*
* Return: The return value of the last executed command.
*/
int main(int argc, char *argv[])
{
int ret = 0, retn;
int *exe_ret = &retn;
char *prompt = "$ ", *new_line = "\n";
name = argv[0];
hist = 1;
aliases = NULL;
signal(SIGINT, sig_handler);
*exe_ret = 0;
environ = _copyenv();
if (!environ)
exit(-100);
if (argc != 1)
{
ret = proc_file_commands(argv[1], exe_ret);
free_env();
free_alias_list(aliases);
return (*exe_ret);
}
if (!isatty(STDIN_FILENO))
{
while (ret != END_OF_FILE && ret != EXIT)
ret = handle_args(exe_ret);
free_env();
free_alias_list(aliases);
return (*exe_ret);
}
while (1)
{
write(STDOUT_FILENO, prompt, 2);
ret = handle_args(exe_ret);
if (ret == END_OF_FILE || ret == EXIT)
{
if (ret == END_OF_FILE)
write(STDOUT_FILENO, new_line, 1);
free_env();
free_alias_list(aliases);
exit(*exe_ret);
}
}
free_env();
free_alias_list(aliases);
return (*exe_ret);
}