Lab1: Xv6 and Unix utilities

sleep

cpp 复制代码
#include "kernel/types.h"
#include "user/user.h"

int main(int argc, char *argv[])
{
	if (argc < 2)
	{
		fprintf(2, "sleep: missing operand\n");
		exit(1);
	}

    int ret = sleep(atoi(argv[1]));

    if (ret == -1)
    {
        exit(1);
    }
    
	exit(0);
}

pingpong

cpp 复制代码
#include "kernel/types.h"
#include "user/user.h"

int main(void)
{
    int fd1[2];
    int fd2[2];
    int pid;
    char buf[1] = {'a'};

    pipe(fd1);
    pipe(fd2);

    pid = fork();

    if (pid == 0)
    {
        close(fd1[0]);
        close(fd2[1]);
        write(fd1[1],buf,sizeof(buf));
        printf("%d: received ping\n",getpid());
        read(fd2[0],buf,sizeof(buf));
    }
    else
    {
        close(fd1[1]);
        close(fd2[0]);
        read(fd1[0],buf,sizeof(buf));
        printf("%d: received pong\n",getpid());
        write(fd2[1],buf,sizeof(buf));
    }
    
	exit(0);
}

primes

cpp 复制代码
#include "kernel/types.h"
#include "user/user.h"

void prime(int fd)
{   
    int num;

    if (read(fd, &num, 4) == 0)
    {
        close(fd);
        return;
    }

    printf("prime %d\n", num);

    int p[2];

    pipe(p);

    int pid = fork();

    if (pid > 0)
    {  
        close(p[0]);
        int n;
        while ((read(fd, &n, 4)) != 0)
        {
            if (n % num != 0)
            {
                write(p[1], &n, 4);
            }     
        }
        close(p[1]);
        wait(0);     
    }
    else
    {
        close(p[1]);
        prime(p[0]);
    }
}

int main(void)
{
    int p[2];

    pipe(p);

    int pid = fork();

    if (pid > 0)
    {
        close(p[0]);
        for (int i = 2; i <= 35; i++)
        {
            write(p[1], &i, 4);
        }
        close(p[1]);
    }
    else
    {
        close(p[1]);
        prime(p[0]);
    }

    exit(0);
}
相关推荐
seasonsyy26 分钟前
在虚拟机中安装操作系统需要U盘吗?
windows·操作系统·vmware·虚拟机
fakerth5 小时前
【OpenHarmony】升级服务组件(UpdateService)
操作系统·openharmony
fakerth8 小时前
【OpenHarmony】Updater 升级包安装组件
操作系统·openharmony
AlexMercer10121 天前
【操作系统】操作系统期末考试 简答题 焚决
c语言·经验分享·笔记·操作系统
brave and determined2 天前
ESP32 FreeRTOS (day1)入门教程 (ESP-IDF版):从超级循环到多任务的系统化思维
操作系统·esp32·freertos·任务·任务调度器·任务控制块·嵌入式设计
Sahm5k2 天前
win10的恢复分区导致C盘无法扩展卷
windows·操作系统
zfj3213 天前
计算机中的 DMA是什么技术
linux·服务器·网络·操作系统·dma
一个平凡而乐于分享的小比特3 天前
公钥与私钥完全解析:数字世界的钥匙与锁
操作系统·密码学·公钥与私钥·隐私安全
小林up3 天前
【MIT-OS6.S081笔记5】Chapter5阅读摘要:Interrupts and device drivers
操作系统·xv6
让流萤再次伟大4 天前
MIT 6.S081 Lab 1. Xv6 and Unix utilities
操作系统