实验环境
VMware Ubuntu20.04 + xv6-labs-2021
1. 实验内容与要求
阅读Lab: Xv6 and Unix utilities中的sleep,pingpong两个任务。在报告中提供相关代码及解释,并提供运行的屏幕截图。
编写user/sleep.c 暂定指定的ticks时间。
编写user/pingpong.c 使用UNIX系统在两个进程间通过管道”ping pong”一个字节。
2. 实验过程
按照提示下载xv6-labs-2021安装包:$ git clone git://g.csail.mit.edu/xv6-labs-2021
进入目录后切换到util分支:$ cd xv6-labs-2021 $ git checkout util
build and run xv6:$ make qemu
Makefile 的UPROGS中添加
UPROGS=\
//...
$U/_sleep\
$U/_pingpong\
sleep.c代码
#include "kernel/types.h"
#include "user/user.h"
int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(2,"sleep.c: wants 1 parameters, get %d parameter(s).\n",argc-1);
exit(1);
}
int time;
time = atoi(argv[1]);//user/ulib.c中定义的的字符串转数字函数
// If time == 0, return ASAP.
if (time <= 0) exit(1);
sleep(time);
exit(0);
}
sleep运行截图:
运行sleep后出现明显的停顿
运行./grade-lab-util sleep对其验证
参考xv6 book中第一章Pipe的内容,完成pingpong
pingpong.c代码
#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
int main(int argc, char *argv[]){
int p1[2];
int p2[2];
pipe(p1);//创建管道
pipe(p2);
int pid = fork();//创建子进程,子进程会复制父进程
if(pid == 0){
close(p1[1]);
close(p2[0]);
char son[2];
read(p1[0],son,1); //读取管道内容
close(p1[0]);
printf("%d: received ping\n",getpid());//getpid获取进程ID
write(p2[1],"a",2);//向管道写入内容
close(p2[1]);
}else if(pid > 0){
close(p1[0]);
close(p2[1]);
write(p1[1],"a",2);
close(p1[1]);
char father[2];
read(p2[0],father,1);
printf("%d: received pong\n",getpid());
close(p2[0]);
}
exit(0);
}
运行结果
版权声明:本文为m0_51273386原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。