aboutsummaryrefslogtreecommitdiff
path: root/smash/main.c
blob: ed41b70d597531dad1ce510510c6ee5d2d6a3dc0 (plain)
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
#include "exec.h"

#include "../lib/sys/io.h"
#include "../lib/cstr/cstr.h"
#include "../lib/sys/dup2.h"

#include "../lib/io/io.h"
#include "../lib/sys/errno.h"

#define BUFSIZ 1024

void clear_buf(char *buf)
{
	for (int i = 0; i < BUFSIZ; ++i)
		buf[i] = 0;
}

int main(int argc, char *argv[], char *envp[])
{
	char buf[BUFSIZ] = {0};
	char prompt[] = "$ ";
	u64 line_length;
	int fd = STDIN_FD;

	if (argc == 2) {
		fd = open(argv[1], OPEN_READ_ONLY, 0);

		if (fd < 0)
			wstdf("%s\n", errstr[-fd]);
	}

	while (1) {
		if (fd == STDIN_FD)
			write(STDOUT_FD, prompt, cstr_length(prompt));
		int p = read(fd, buf, BUFSIZ);
		line_length = cstr_length(buf);


		if (line_length == 0)
			break;

		if (buf[line_length - 1] == '\n')
			buf[--line_length] = 0;

		if (line_length > 0) {
			exec(buf);
		}

		clear_buf(buf);
	}

	if (fd != STDOUT_FD)
		close(fd);
}