【MIT 6.S081】Lab1: Xv6 and Unix utilities

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


本Lab包括五个简单程序的实现,初步熟悉系统调用接口。
笔者用时约6h(我太菜辣)

概述

根据文档说明,我们需要把写的每个程序文件放在user文件夹下,并且在MakeFileUPROGS添加相应的程序名,这样子就可以在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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值