实验内容网址:https://xv6.dgs.zone/labs/requirements/lab1.html
Sleep
关键点:函数参数判断、系统函数调用
思路:
通过argc来判断函数参数是否正确,通过atoi函数来讲字符串转化为整型,调用sleep函数后退出程序。
代码:
#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
int
main(int argc, char *argv[])
{
int time;
if(argc != 2){
printf("usage:%s timexx\n",argv[0]);
exit(-1);
}
time = atoi(argv[1]);
sleep(time);
exit(0);
}
Pingpong
关键点:
pipe()、fork()、read()、write()、getpid()
思路:
管道是作为一对文件描述符公开给进程的小型内核缓冲区,一个用于读取,一个用于写入。将数据写入管道的一端使得这些数据可以从管道的另一端读取。
其初始化方式为:
int p[2];
pipe(p);
// p[0]是管道的读取端
// P[1]是管道的写入端
根据题目要求,父进程和子进程都需要向对方发送字节,那么可以定义2个管道,代码如下
#define READ 0
#define WRITE 1
int father2child[2];
int child2father[2];
pipe(father2child);
pipe(child2father);
创建进程使用fork 函数,在父进程中,fork返回子类的PID;在子进程中,fork返回零。
步骤:
- 新建 pingpong.c文件,并在MakeFile文件的UPROGS中加入程序。
- 编写如下的代码,运行make qemu进行编译并运行pingpong.
#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
#define READ 0
#define WRITE 1
int
main(int argc, char *argv[])
{
int father2child[2];
int child2father[2];
char sendByte = 'A';
pipe(father2child);
pipe(child2father);
if(fork() == 0){
// 子进程
// 管道关闭,这两个方向的管道不需要使用(感觉不用也可以,可以代码写完再看看哪里需要关闭)
close(father2child[WRITE]);
close(