本Lab包括五个简单程序的实现,初步熟悉系统调用接口。
笔者用时约6h(我太菜辣)
概述
根据文档说明,我们需要把写的每个程序文件放在user文件夹下,并且在MakeFile的UPROGS添加相应的程序名,这样子就可以在qemu中直接用命令行指令调用相应的程序啦。如下图所示。

sleep
sleep程序接收一个参数,调用库函数sleep进行睡眠即可,没啥好说滴。
#include "kernel/types.h"
#include "user/user.h"
int main(int argc, char* argv[])
{
if (argc != 2) {
fprintf(2, "usage: sleep time\n");
exit(1);
}
sleep(atoi(argv[1]));
exit(0);
}
pingpong
该程序的要求就是创建一个子进程,父进程为子进程发送一个字节,子进程接收到字节之后,打印ping,向父进程发送一个字节,父进程接收到该字节之后打印pong,程序结束。
做法就是打开两个管道,一个用于父进程写子进程读,另一个则相反。
#include "kernel/types.h"
#include "user/user.h"
int main(int argc, char* argv[])
{
if (argc != 1) {
fprintf(2, "usage: pingpong\n");
exit(1);
}
int p_father_to_child[2];
int p_child_to_father[2];
if (pipe(p_father_to_child) == -1 || pipe(p_child_to_father) == -1) {
fprintf(2, "failed to open pipe\n");
exit(1);
}
char buf = 'C';
int exit_state = 0;
// child process
if (fork() == 0) {
close(p_father_to_child[1]);
close(p_child_to_father[0]);
if (read(p_father_to_child[0], &buf, 1) != 1) {
fprintf(2, "failed to read pipe in child\n");
exit_state = 1;
}
fprintf(1, "%d: received ping\n", getpid());
if (write(p_child_to_father[1], &buf, 1) != 1) {
fprintf(2, "failed to write pipe in child\n");
exit_state = 1;
}
exit(exit_state);
}
// father process
close(p_father_to_child[0]);
close(p_child_to_father[1]);
if (write(p_father_to_child

本文介绍了五个简单的操作系统程序实现,包括sleep、pingpong、primes、find和xargs。这些程序涉及到进程创建、管道通信、素数筛选以及命令行参数处理等系统调用接口的使用。
最低0.47元/天 解锁文章
2332

被折叠的 条评论
为什么被折叠?



