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);
}
相关推荐
望获linux2 小时前
【Linux 基础知识系列】第二篇-Linux 发行版概述
linux·数据库·postgresql·操作系统·开源软件·rtos·嵌入式软件
code monkey.8 小时前
【寻找Linux的奥秘】第八章:进程控制
linux·操作系统·进程
Nelson_hehe18 小时前
考研系列-操作系统:第二章、进程与线程
操作系统·线程·进程·进程调度·408考研
潇-xiao2 天前
Linux系统-基本指令(3)
linux·笔记·操作系统
望获linux4 天前
实时操作系统革命:实时Linux驱动的智能时代底层重构
linux·运维·重构·操作系统·开源软件·嵌入式软件
EQUINOX14 天前
MIT 6.S081 2020Lab5 lazy page allocation 个人全流程
操作系统
望获linux6 天前
工业RTOS生态重构:从PLC到“端 - 边 - 云”协同调度
linux·人工智能·自动化·操作系统·开源软件·制造·嵌入式软件
眸生7 天前
自制操作系统day7(获取按键编码、FIFO缓冲区、鼠标、键盘控制器(Keyboard Controller, KBC)、PS/2协议)
c语言·汇编·计算机外设·操作系统·计算机组成原理·寄存器
weixin_472339467 天前
页面置换算法概述
操作系统
眸生7 天前
自制操作系统day8 (鼠标数据取得、通往32位模式之路、A20GATE、切换到保护模式、控制寄存器cr0-cr4以及cr8、ALIGNB)
c语言·汇编·计算机外设·操作系统·i/o外设