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篇章】Linux 进程信号1:解锁系统高效运作的 “隐藏指令”,开启性能飞跃新征程(精讲信号产生和保存)
linux·运维·服务器·学习·操作系统·进程信号
望获linux3 天前
北京亦庄机器人马拉松:人机共跑背后的技术突破与产业启示
linux·人工智能·机器人·操作系统·开源软件·rtos·具身智能
獭.獭.3 天前
Linux -- 操作系统
linux·操作系统·冯诺依曼体系
红白小蛋糕4 天前
《操作系统真象还原》调试总结篇
操作系统·内核·开发笔记
望获linux5 天前
望获实时Linux系统荣获人形机器人技术突破奖
linux·运维·机器人·操作系统·开源软件·rtos
ssslar6 天前
MIT XV6 - 1.1 Lab: Xv6 and Unix utilities - sleep 是怎样练成的?
操作系统·risc-v·xv6
vortex56 天前
Windows权限与icacls命令详解
windows·网络安全·渗透测试·操作系统
tinker7 天前
Ubuntu 共享网络配置
操作系统
LUCIAZZZ7 天前
分布式链路追踪理论
java·分布式·中间件·操作系统·链路追踪
易保山7 天前
MIT6.S081 - Lab11 networking(网络栈)
linux·操作系统·c