操作系统原理作业(二):xv6 shell编程作业之实现shell的基础命令

作业题目

要求在原有代码的基础上,实现shell的三类基础命令,它们包括:

  1. 简单命令(可执行的程序命令,如ls等)
  2. I/O重定向命令,如:
1
2
$ echo "6.828 is cool" > x.txt
$ cat < x.txt
  1. 管道命令(pipe),如:
1
$ ls | sort | uniq | wc

设计思路

原有代码中定义了输入命令的基础结构体,即 struct cmd。这个结构体就一个成员type,用于记录输入命令的类型: ‘ ‘ 表示简单可执行命令 ‘|’ 表示管道命令, ‘<’ 和’>’ 表示I/O重定向命令。

1
2
3
struct cmd {
int type; // ' ' (exec), | (pipe), '<' or '>' for redirection
};

每一个类型分别继承cmd基础结构体,派生出对应的三类结构体:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct execcmd {
int type; // ' '
char *argv[MAXARGS]; // arguments to the command to be exec-ed
};
struct redircmd {
int type; // < or >
struct cmd *cmd; // the command to be run (e.g., an execcmd)
char *file; // the input/output file
int mode; // the mode to open the file with
int fd; // the file descriptor number to use for the file
};
struct pipecmd {
int type; // |
struct cmd *left; // left side of pipe
struct cmd *right; // right side of pipe
};

经过分析,设计了以下的运行流程,其中,管道命令的解析和运行是通过递归函数实现的。

具体实现

在所给代码中,void runcmd(struct cmd *cmd)这个函数是真正驱动调用实现shell基础功能的核心。通过调用系统接口函数 execv(), open(), close(), dup(), pipe()和在原有代码的基础上,来实现目标功能。

实现简单命令

1
2
3
4
5
6
7
// In the method runcmd()
ecmd = (struct execcmd*)cmd;
if(ecmd->argv[0] == 0)
exit(EXIT_SUCCESS);
execv(search_path(ecmd->argv[0]), ecmd->argv);
fprintf(stderr, "execv returned with error: %s\n", strerror(errno));
exit(EXIT_FAILURE);
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
char * search_path(char *exe)
{
DIR *d;
struct dirent *dir;
char *paths = getenv("PATH");
char *path_dir = strtok(paths, ":");
while (path_dir != NULL) {
d = opendir(path_dir);
if (d == NULL) {
fprintf(stderr, "cannot open dir: %s", strerror(errno));
} else {
while ((dir = readdir(d)) != NULL) {
if (strcmp(dir->d_name, exe) == 0) {
char *final_path = malloc(strlen(path_dir) + strlen(exe) + 2);
final_path = strcat(final_path, path_dir);
final_path = strcat(final_path, "/");
final_path = strcat(final_path, exe);
return final_path;
}
}
}
path_dir = strtok(NULL, ":");
}
return exe;
}

实现I/O重定向命令

1
2
3
4
// In the method runcmd()
rcmd = (struct redircmd*)cmd;
setup_redirection(rcmd);
runcmd(rcmd->cmd);
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
void setup_redirection(struct redircmd *cmd)
{
int redirection_fd = 0;
if (cmd->type == '>') {
// output redirection
redirection_fd = open(cmd->file, cmd->mode, S_IRWXU);
}
else {
// input redirection
redirection_fd = open(cmd->file, cmd->mode);
}
if (redirection_fd < 0) {
fprintf(stderr, "failed to open file for redirection: %s\n",\
strerror(errno));
exit(EXIT_FAILURE);
}
dup2_wrapped(redirection_fd, cmd->fd);
}
// wrapper around the dup2 system call used to check for errors
void dup2_wrapped(int old_fd, int new_fd)
{
int result = dup2(old_fd, new_fd);
if (result < 0) {
fprintf(stderr, "failed to dup file descriptors: %s\n", \
strerror(errno));
exit(EXIT_FAILURE);
}
}

实现管道(pipe)命令

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
// In the method runcmd()
pcmd = (struct pipecmd*)cmd;
int result = pipe(p);
if (result == -1)
{
fprintf(stderr, "pipe system call did not complete successfully: %s\n",\
strerror(errno));
exit(EXIT_FAILURE);
}
if (fork1() == 0)
{
// child1 executes pcmd->left
close(p[0]);
dup2_wrapped(p[1], STDOUT_FILENO);
close(p[1]);
runcmd(pcmd->left);
}
if (fork1() == 0)
{
// child2 executes pcmd->right
close(p[1]);
dup2_wrapped(p[0], STDIN_FILENO);
close(p[0]);
runcmd(pcmd->right);
}
close(p[0]);
close(p[1]);
wait(&r);
wait(&r);
exit(EXIT_SUCCESS);

完整代码

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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <assert.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <dirent.h>
// Simplifed xv6 shell.
#define MAXARGS 10
// All commands have at least a type. Having looked at the type, the code
// typically casts the *cmd to some specific cmd type.
struct cmd {
int type; // ' ' (exec), | (pipe), '<' or '>' for redirection
};
struct execcmd {
int type; // ' '
char *argv[MAXARGS]; // arguments to the command to be exec-ed
};
struct redircmd {
int type; // < or >
struct cmd *cmd; // the command to be run (e.g., an execcmd)
char *file; // the input/output file
int mode; // the mode to open the file with
int fd; // the file descriptor number to use for the file
};
struct pipecmd {
int type; // |
struct cmd *left; // left side of pipe
struct cmd *right; // right side of pipe
};
int fork1(void); // Fork but exits on failure.
struct cmd *parsecmd(char*);
void setup_redirection(struct redircmd*);
void dup2_wrapped(int, int);
char *search_path(char*); // Recursively search through all paths listed
// in $PATH to find the given executabe
// Execute cmd. Never returns. Executes in the child.
void
runcmd(struct cmd *cmd)
{
int p[2], r;
struct execcmd *ecmd;
struct pipecmd *pcmd;
struct redircmd *rcmd;
if(cmd == 0)
exit(EXIT_SUCCESS);
errno = 0;
switch(cmd->type){
default:
fprintf(stderr, "unknown commnad type\n");
exit(EXIT_FAILURE);
case ' ':
ecmd = (struct execcmd*)cmd;
if(ecmd->argv[0] == 0)
exit(EXIT_SUCCESS);
execv(search_path(ecmd->argv[0]), ecmd->argv);
fprintf(stderr, "execv returned with error: %s\n", strerror(errno));
exit(EXIT_FAILURE);
case '>':
case '<':
rcmd = (struct redircmd*)cmd;
setup_redirection(rcmd);
runcmd(rcmd->cmd);
case '|':
pcmd = (struct pipecmd*)cmd;
int result = pipe(p);
if (result == -1) {
fprintf(stderr, "pipe system call did not complete successfully: %s\n",\
strerror(errno));
exit(EXIT_FAILURE);
}
if (fork1() == 0) { // child1 executes pcmd->left
close(p[0]);
dup2_wrapped(p[1], STDOUT_FILENO);
close(p[1]);
runcmd(pcmd->left);
}
if (fork1() == 0) { // child2 executes pcmd->right
close(p[1]);
dup2_wrapped(p[0], STDIN_FILENO);
close(p[0]);
runcmd(pcmd->right);
}
close(p[0]);
close(p[1]);
wait(&r);
wait(&r);
exit(EXIT_SUCCESS);
}
exit(EXIT_FAILURE); // should never get here
}
void
setup_redirection(struct redircmd *cmd)
{
int redirection_fd = 0;
if (cmd->type == '>') { // output redirection
redirection_fd = open(cmd->file, cmd->mode, S_IRWXU);
} else { // input redirection
redirection_fd = open(cmd->file, cmd->mode);
}
if (redirection_fd < 0) {
fprintf(stderr, "failed to open file for redirection: %s\n",\
strerror(errno));
exit(EXIT_FAILURE);
}
dup2_wrapped(redirection_fd, cmd->fd);
}
// wrapper around the dup2 system call used to check for errors
void
dup2_wrapped(int old_fd, int new_fd)
{
int result = dup2(old_fd, new_fd);
if (result < 0) {
fprintf(stderr, "failed to dup file descriptors: %s\n", \
strerror(errno));
exit(EXIT_FAILURE);
}
}
// List through directories in $PATH to find given executable.
// Returns the given executable if not found in any of the $PATH
// directoties.
char *
search_path(char *exe)
{
DIR *d;
struct dirent *dir;
char *paths = getenv("PATH");
char *path_dir = strtok(paths, ":");
while (path_dir != NULL) {
d = opendir(path_dir);
if (d == NULL) {
fprintf(stderr, "cannot open dir: %s", strerror(errno));
} else {
while ((dir = readdir(d)) != NULL) {
if (strcmp(dir->d_name, exe) == 0) {
char *final_path = malloc(strlen(path_dir) + strlen(exe) + 2);
final_path = strcat(final_path, path_dir);
final_path = strcat(final_path, "/");
final_path = strcat(final_path, exe);
return final_path;
}
}
}
path_dir = strtok(NULL, ":");
}
return exe;
}
int
getcmd(char *buf, int nbuf)
{
if (isatty(fileno(stdin)))
fprintf(stdout, "6.828$ ");
memset(buf, 0, nbuf);
fgets(buf, nbuf, stdin);
if(buf[0] == 0) // EOF
return -1;
return 0;
}
int
main(void)
{
static char buf[100];
int r;
// Read and run input commands.
while(getcmd(buf, sizeof(buf)) >= 0){
if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' '){
// Clumsy but will have to do for now.
// Chdir has no effect on the parent if run in the child.
buf[strlen(buf)-1] = 0; // chop \n
if(chdir(buf+3) < 0)
fprintf(stderr, "cannot cd %s\n", buf+3);
continue;
}
if(fork1() == 0)
runcmd(parsecmd(buf));
wait(&r);
}
exit(EXIT_SUCCESS);
}
int
fork1(void)
{
int pid;
pid = fork();
if(pid == -1)
perror("fork");
return pid;
}
struct cmd*
execcmd(void)
{
struct execcmd *cmd;
cmd = malloc(sizeof(*cmd));
memset(cmd, 0, sizeof(*cmd));
cmd->type = ' ';
return (struct cmd*)cmd;
}
struct cmd*
redircmd(struct cmd *subcmd, char *file, int type)
{
struct redircmd *cmd;
cmd = malloc(sizeof(*cmd));
memset(cmd, 0, sizeof(*cmd));
cmd->type = type;
cmd->cmd = subcmd;
cmd->file = file;
cmd->mode = (type == '<') ? O_RDONLY : O_WRONLY|O_CREAT|O_TRUNC;
cmd->fd = (type == '<') ? 0 : 1;
return (struct cmd*)cmd;
}
struct cmd*
pipecmd(struct cmd *left, struct cmd *right)
{
struct pipecmd *cmd;
cmd = malloc(sizeof(*cmd));
memset(cmd, 0, sizeof(*cmd));
cmd->type = '|';
cmd->left = left;
cmd->right = right;
return (struct cmd*)cmd;
}
// Parsing
char whitespace[] = " \t\r\n\v";
char symbols[] = "<|>";
int
gettoken(char **ps, char *es, char **q, char **eq)
{
char *s;
int ret;
s = *ps;
while(s < es && strchr(whitespace, *s))
s++;
if(q)
*q = s;
ret = *s;
switch(*s){
case 0:
break;
case '|':
case '<':
s++;
break;
case '>':
s++;
break;
default:
ret = 'a';
while(s < es && !strchr(whitespace, *s) && !strchr(symbols, *s))
s++;
break;
}
if(eq)
*eq = s;
while(s < es && strchr(whitespace, *s))
s++;
*ps = s;
return ret;
}
int
peek(char **ps, char *es, char *toks)
{
char *s;
s = *ps;
while(s < es && strchr(whitespace, *s))
s++;
*ps = s;
return *s && strchr(toks, *s);
}
struct cmd *parseline(char**, char*);
struct cmd *parsepipe(char**, char*);
struct cmd *parseexec(char**, char*);
// make a copy of the characters in the input buffer, starting from s through es.
// null-terminate the copy to make it a string.
char
*mkcopy(char *s, char *es)
{
int n = es - s;
char *c = malloc(n+1);
assert(c);
strncpy(c, s, n);
c[n] = 0;
return c;
}
struct cmd*
parsecmd(char *s)
{
char *es;
struct cmd *cmd;
es = s + strlen(s);
cmd = parseline(&s, es);
peek(&s, es, "");
if(s != es){
fprintf(stderr, "leftovers: %s\n", s);
exit(-1);
}
return cmd;
}
struct cmd*
parseline(char **ps, char *es)
{
struct cmd *cmd;
cmd = parsepipe(ps, es);
return cmd;
}
struct cmd*
parsepipe(char **ps, char *es)
{
struct cmd *cmd;
cmd = parseexec(ps, es);
if(peek(ps, es, "|")){
gettoken(ps, es, 0, 0);
cmd = pipecmd(cmd, parsepipe(ps, es));
}
return cmd;
}
struct cmd*
parseredirs(struct cmd *cmd, char **ps, char *es)
{
int tok;
char *q, *eq;
while(peek(ps, es, "<>")){
tok = gettoken(ps, es, 0, 0);
if(gettoken(ps, es, &q, &eq) != 'a') {
fprintf(stderr, "missing file for redirection\n");
exit(-1);
}
switch(tok){
case '<':
cmd = redircmd(cmd, mkcopy(q, eq), '<');
break;
case '>':
cmd = redircmd(cmd, mkcopy(q, eq), '>');
break;
}
}
return cmd;
}
struct cmd*
parseexec(char **ps, char *es)
{
char *q, *eq;
int tok, argc;
struct execcmd *cmd;
struct cmd *ret;
ret = execcmd();
cmd = (struct execcmd*)ret;
argc = 0;
ret = parseredirs(ret, ps, es);
while(!peek(ps, es, "|")){
if((tok=gettoken(ps, es, &q, &eq)) == 0)
break;
if(tok != 'a') {
fprintf(stderr, "syntax error\n");
exit(-1);
}
cmd->argv[argc] = mkcopy(q, eq);
argc++;
if(argc >= MAXARGS) {
fprintf(stderr, "too many args\n");
exit(-1);
}
ret = parseredirs(ret, ps, es);
}
cmd->argv[argc] = 0;
return ret;
}

运行结果

简单命令

I/O重定向命令

管道(pipe)命令

坚持原创技术分享,您的支持将鼓励我继续创作!

热评文章