HW2 shell

shell

1、阅读 xv6 book 的第 0 章:点击下载

2、下载 6.828 shell 文件:点击下载

3、将下列代码粘贴到 t.sh 文件内

1
2
3
4
5
6
ls > y
cat < y | sort | uniq | wc > y1
cat y1
rm y1
ls | sort | uniq | wc
rm y

4、编译并且执行

1
2
gcc -o sh sh.c
./sh < t.sh

sh

产生了错误,没有实现,接下来进行实现。

Executing simple commands

实现 ls

查看 exec manual 页,阅读 execv 并且答应错误信息当 exec 失败的时候,然后实现 ls 的 case 命令,根据 type 定义,我们只需要实现 case ‘ ‘ 的情况:

execv 参数

1
2
3
4
5
6
7
8
9
10
11
case ' ':
ecmd = (struct execcmd*)cmd;
if(ecmd->argv[0] == 0)
_exit(0);
// fprintf(stderr, "exec not implemented\n");
// Your code here ...
int res = execv(ecmd->argv[0],ecmd->argv);
if(res == -1){
fprintf(stderr,"exec fails!\n");
}
break;

/bin/ls

I/O redirection

直接参照 xv6-book 实现重定向就 ok,关闭当前进程的文件描述符,而文件描述符总是从最小的开始增长,所以当我们打开一个文件时,我们将输入/输出的标准描述符绑定到该文件上边儿,然后跑 runcmd 就可以直接使用了,完成I/O 重定向:

1
2
3
4
5
6
7
8
9
10
11
12
13
case '>':
case '<':
rcmd = (struct redircmd*)cmd;
//fprintf(stderr, "redir not implemented\n");
// Your code here ...
close(rcmd->fd);
int fd = open(rcmd->file,rcmd->flags,O_CREAT|O_WRONLY|O_RDONLY);
if(fd == -1){
fprintf(stderr,"could not open file %s\n", rcmd->file);
_exit(1);
}
runcmd(rcmd->cmd);
break;

/bin/cat < x.txt

Implement pipes

手动实现一个管道,参考讲义中的管道,直接写,我们将父进程的标准输出绑定到管道的一端,将子进程的标准输出绑定到管道的另一端,这样就可以实现父进程从管道的一端输出,子进程从管道的一端输入,然后我们让子进程跑在管道的左端,父进程跑在管道的右端,父进程等待子进程完成并且退出再执行:

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
case '|':
pcmd = (struct pipecmd*)cmd;
//fprintf(stderr, "pipe not implemented\n");
// Your code here ...
int pipefd[2];
pipe(pipefd);

int process = fork1();
if(process == 0){
// child process
// pipe left side
close(1);
dup(pipefd[1]);
close(pipefd[0]);
close(pipefd[1]);
runcmd(pcmd->left);
}
else{
// parent process
// pipe right side
close(0);
dup(pipefd[0]);
close(pipefd[0]);
close(pipefd[1]);
wait(0);
runcmd(pcmd->right);
}
break;

手动补全 tt.sh 文件,然后尝试看能否正确运行

1
2
3
4
5
6
7
8

/bin/ls > y
/bin/cat < y | /bin/sort | /bin/uniq | /bin/wc > y1
/bin/cat y1
/bin/rm y1
/bin/ls | /bin/sort | /bin/uniq | /bin/wc
/bin/rm y

pipe test


HW2 shell
https://www.bencorn.com/2021/08/13/HW2-shell/
作者
Bencorn
发布于
2021年8月13日
许可协议