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);
}
相关推荐
脑子慢且灵1 天前
计算机操作系统——存储器管理
linux·服务器·windows·操作系统·存储器·存储器多级结构
易保山1 天前
MIT6.S081 - Lab7 Locks(锁优化 | 并发安全)
linux·操作系统·c
塞尔维亚大汉2 天前
【鸿蒙南向开发】标准系统方案之瑞芯微RK3566移植案例(下)
操作系统·嵌入式·harmonyos
知识浅谈2 天前
【Windows】如何在任意文件夹中右键打开cmd终端
操作系统
罗念笙2 天前
操作系统中的进程有哪几种状态?
操作系统
OpenAnolis小助手4 天前
龙蜥社区荣获 OS2ATC 2025 “最具影响力开源创新贡献奖”
开源·操作系统·龙蜥社区·龙蜥·openanolis·行业认可
_清浅5 天前
JavaScript(JS进阶)
开发语言·前端·javascript·操作系统·html5
Rinai_R5 天前
xv6-labs-2024 lab2
c语言·操作系统·学习笔记·计算机基础·实验
易保山6 天前
MIT6.S081 - Lab7 Multithreading(进程调度)
linux·操作系统·c
塞尔维亚大汉6 天前
【鸿蒙南向开发】轻量和小型系统三方库移植指南(一)
操作系统·嵌入式·harmonyos