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);
}
相关推荐
大数据新鸟5 小时前
信号(Signal) vs 信号量(Semaphore)
操作系统
A-刘晨阳1 天前
麒麟v10桌面版2403版本运行程序提示权限不足(KYSEC)
运维·云计算·操作系统·银河麒麟·麒麟桌面系统
a里啊里啊2 天前
常见面试题目集合
linux·数据库·c++·面试·职场和发展·操作系统
方安乐4 天前
win10专业版如何禁止更新至win11
操作系统
艾莉丝努力练剑4 天前
【Linux系统:多线程】线程概念与控制
linux·运维·服务器·c++·后端·学习·操作系统
凉、介6 天前
Flash 块设备驱动开发
c语言·驱动开发·笔记·学习·操作系统·嵌入式
.普通人7 天前
freertos源码解析(里面的源码来源于另一个博主,我这里只是讲一下我自己的理解)
操作系统·rtos
努力的章鱼bro7 天前
操作系统-net
c++·操作系统·dma·risc-v
努力的章鱼bro9 天前
操作系统-FileSystem
c++·操作系统·risc-v·filesystem
muls110 天前
java面试宝典
java·linux·服务器·网络·算法·操作系统