-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
116 lines (94 loc) · 2.07 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
/*
@author: Huzaifa Naseer
*/
#include "executor.h"
#include "parser.h"
#include "shell.h"
#include "source.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
printf("\033[1;32m");
printf("Welcome to my shell!\n");
printf("This shell was created by @HuzaifaNaseer.\n");
printf("Check out my GitHub: https://github.com/HN026\n");
printf(
"Connect with me on LinkedIn: https://linkedin.com/in/huzaifanaseer\n");
printf("\033[0m");
char *cmd;
initsh();
do {
print_prompt1();
cmd = read_cmd();
if (!cmd) {
exit(EXIT_SUCCESS);
}
if (cmd[0] == '\0' || strcmp(cmd, "\n") == 0) {
free(cmd);
continue;
}
if (strcmp(cmd, "exit\n") == 0) {
free(cmd);
break;
}
struct source_s src;
src.buffer = cmd;
src.bufsize = strlen(cmd);
src.curpos = INIT_SRC_POS;
parse_and_execute(&src);
} while (1);
exit(EXIT_SUCCESS);
}
char *read_cmd(void) {
char buf[1024];
char *ptr = NULL;
char ptrlen = 0;
while (fgets(buf, 1024, stdin)) {
int buflen = strlen(buf);
if (!ptr) {
ptr = malloc(buflen + 1);
} else {
char *ptr2 = realloc(ptr, ptrlen + buflen + 1);
if (ptr2) {
ptr = ptr2;
} else {
free(ptr);
ptr = NULL;
}
}
if (!ptr) {
fprintf(stderr, "error: failed to alloc buffer: %s\n", strerror(errno));
return NULL;
}
strcpy(ptr + ptrlen, buf);
if (buf[buflen - 1] == '\n') {
if (buflen == 1 || buf[buflen - 2] != '\\') {
return ptr;
}
ptr[ptrlen + buflen - 2] = '\0';
buflen -= 2;
print_prompt2();
}
ptrlen += buflen;
}
return ptr;
}
int parse_and_execute(struct source_s *src) {
skip_white_spaces(src);
struct token_s *tok = tokenize(src);
if (tok == &eof_token) {
return 0;
}
while (tok && tok != &eof_token) {
struct node_s *cmd = parse_command(tok);
if (!cmd) {
break;
}
do_command(cmd);
free_node_tree(cmd);
tok = tokenize(src);
}
return 1;
}