-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathmsh.c
More file actions
89 lines (69 loc) · 1.35 KB
/
msh.c
File metadata and controls
89 lines (69 loc) · 1.35 KB
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
#include <sys/file.h>
#include <string.h>
#include <util.h>
#include "msh.h"
static void parsefd(CTX, int fd)
{
char inbuf[2048];
int rd;
while((rd = sys_read(fd, inbuf, sizeof(inbuf))) > 0) {
parse(ctx, inbuf, rd);
} if(rd < 0) {
quit(ctx, "read", NULL, rd);
};
}
static void parsestr(CTX, char* str)
{
parse(ctx, str, strlen(str));
}
static int openfile(CTX, char* name)
{
int fd;
if((fd = sys_open(name, O_RDONLY | O_CLOEXEC)) < 0)
quit(ctx, "open", name, fd);
if(!ctx->file) {
ctx->file = name;
ctx->line = 1;
}
return fd;
}
#define OPT_c (1<<0)
static int parseopts(CTX, char* str)
{
char* p;
int opts = 0;
for(p = str; *p; p++) switch(*p) {
case 'c': opts |= OPT_c; break;
default: fatal(ctx, "unknown options", str);
}
return opts;
}
int main(int argc, char** argv, char** envp)
{
struct sh ctx;
long fd = STDIN;
char* script = NULL;
int opts = 0;
int i = 1;
memset(&ctx, 0, sizeof(ctx));
ctx.envp = envp;
ctx.errfd = STDERR;
if(i < argc && argv[i][0] == '-')
opts = parseopts(&ctx, argv[i++] + 1);
if(i < argc)
script = argv[i++];
if(!(opts & OPT_c) && script)
fd = openfile(&ctx, script);
if(!(opts & OPT_c))
ctx.line = 1;
ctx.topargc = argc;
ctx.topargp = i;
ctx.topargv = argv;
hinit(&ctx);
if(!(opts & OPT_c))
parsefd(&ctx, fd);
else
parsestr(&ctx, script);
pfini(&ctx);
exit(&ctx, 0);
}