-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
83 lines (70 loc) · 1.52 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
#include "bshell.h"
#define READLINE_BUFSIZE 1024
extern Token *cur;
extern bool syntax_error;
pid_t shell_pgid;
void *bshell_malloc(size_t size) {
void *ptr = malloc(size);
if (!ptr) {
fprintf(stderr, "bshell: allocation error");
exit(EXIT_FAILURE);
}
return ptr;
}
char *bshell_readline() {
int pos = 0;
size_t bufsize = READLINE_BUFSIZE;
char *buffer = (char *)bshell_malloc(bufsize * sizeof(char));
int c;
while (1) {
c = getchar();
if (c == '\n') {
buffer[pos] = '\0';
return buffer;
} else if (c == EOF) {
printf("\n");
exit(-1);
} else {
buffer[pos] = c;
}
pos++;
if (pos > (int)bufsize) {
bufsize += READLINE_BUFSIZE;
buffer = (char *)realloc(buffer, bufsize);
if (!buffer) {
fprintf(stderr, "bshell: allocation error");
exit(EXIT_FAILURE);
}
}
}
}
void bshell_init() {
shell_pgid = getpid();
if (setpgid(shell_pgid, shell_pgid) < 0) {
perror("Couldn't put the shell in its own process group");
exit(EXIT_FAILURE);
}
tcsetpgrp(STDIN_FILENO, shell_pgid);
}
int main() {
bshell_init();
do {
fprintf(stderr, "$ ");
char *line = bshell_readline();
update_job_status(false);
tokenize(line);
Token *head = cur;
if (head) {
ASTNode *root = expr();
if (syntax_error) {
syntax_error = false;
} else {
evaluate_ast(root, true);
}
free_ast(root);
free_tokens(head);
}
free(line);
} while (1);
return 0;
}