-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
67 lines (58 loc) · 1.16 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
#include "tinyshell.h"
int pipe_count;
int I;
bool is_background;
static void run(char ***commands)
{
I = -1;
while (commands[++I])
if (*commands[I])
execute(commands[I]);
while (I-- > 0)
free_strings(commands[I]);
free(commands);
}
static bool read_(char **line, const char *prompt)
{
size_t i = 0, max = 4096;
int letter;
printf("%s", prompt);
*line = malloc(max);
while ((letter = getchar()) != '\n')
{
if (letter == EOF)
exit(EXIT_SUCCESS);
if (i == max)
(*line) = realloc(*line, max *= 2);
(*line)[i++] = letter;
}
(*line)[i] = 0;
return (true);
}
static void check(char *mode, int count, char **arguments)
{
if (count == 1)
*mode = INTERACTIVE;
else if (count == 3 && is_same(arguments[1], "-c"))
*mode = COMMANDLINE;
else
exit_error("check");
}
static void parse_and_run(char *line)
{
char ***commands;
is_background = line[strlen(line) - 1] == '&';
if ((commands = parse(line)))
run(commands);
}
int main(int count, char **arguments)
{
char *line;
char mode;
check(&mode, count, arguments);
if (mode == INTERACTIVE)
while (read_(&line, "tinyshell$ "))
parse_and_run(line);
else
parse_and_run(strdup(arguments[2]));
}