-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell.c
75 lines (71 loc) · 1.48 KB
/
shell.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
#include "main.h"
/**
* main - program starts here.
* @ac: argument count
* @av: argument vector
* Return: always 0.
*/
int main(int ac, char **av)
{
int exit_stat = 0;
char *prompt = "#cisfun~$ ";
int interactive_mode = isatty(STDIN_FILENO);
(void) av;
(void) ac;
while (1)
{
if (interactive_mode)
write(1, prompt, _strlen(prompt));
if (get_cmd(interactive_mode, &exit_stat))
break;
}
exit(exit_stat);
}
/**
* get_cmd - gets a command from stdout and performs action
* @interactive_mode: return of isatty(STDIN_FILENO).
* Return: 0 on success, 1 on error.
*/
int get_cmd(int interactive_mode, int *exit_stat)
{
char *path, **args, *cmd_line = NULL;
size_t size = 0;
struct stat statbuf;
cmd_t cmd_stat = FOUND; /* Command status */
/* getting command from the commandline */
if (_getline(&cmd_line, &size, STDIN_FILENO) == -1)
{
if (interactive_mode)
write(1, "\n", 1);
free(cmd_line);
return (1);
}
ch_handler(cmd_line);
args = tokenize_str(cmd_line, " \n\t"); /* tokenize the command */
free(cmd_line);
if (args[0] == NULL)
{
free(args);
return (0);
}
if (builtin_handler(args, exit_stat) == FOUND)
{
free_grid(args);
return (0);
}
/* Search for command in current path and in PATH */
if (stat(args[0], &statbuf) != 0)
{
cmd_stat = NOT_FOUND;
path = path_handler(args[0]);
if (path != NULL)
{
free(args[0]);
args[0] = path;
cmd_stat = FOUND;
}
}
execute_cmd(args, cmd_stat, exit_stat);
free_grid(args);
return (0);
}