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);
}
相关推荐
布莱克6059 小时前
软中断和硬中断的区别
开发语言·操作系统
噜~噜~噜~1 天前
操作系统笔记-2.3.2.1 进程互斥的软件实现方法
笔记·操作系统
冬奇Lab2 天前
开源项目第198期:Omarchy — DHH 打造的「意见鲜明」Linux 桌面系统
人工智能·开源·操作系统
噜~噜~噜~3 天前
操作系统笔记-2.2.6 多处理机调度
笔记·操作系统
拂拉氏5 天前
【Linux】 开发工具(Makefile、git、cgdb)解析与对于操作系统的基础认识
linux·git·操作系统·makefile·cgdb
程序猿乐锅7 天前
【王道操作系统| 第五章】I/O管理
操作系统
wunaiqiezixin8 天前
MIT 6.S081 xv6 源码精读(Scheduling):sched、scheduler
linux·unix·os·xv6·mit6.s081
我爱cope8 天前
【操作系统 | 管程、消息通信、屏障与 RCU:并发协作的几种组织方式】
学习·操作系统
程序猿乐锅8 天前
【王道操作系统| 第三章】内存管理
操作系统
mifengxing10 天前
操作系统 文件系统
笔记·操作系统·计算机408