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);
}
相关推荐
charlie1145141912 天前
Cinux: 为大内核铺路
开发语言·c++·操作系统·现代c++
饼干哥哥2 天前
每晚300+个爆款疯狂跑,0人值守TikTok工厂开张!!
后端·操作系统·产品
小宇子2B3 天前
文件页怎么回收:page cache、干净页和脏页
操作系统
m0_547486663 天前
《系统级编程及分布式应用实现技术》 全套PPT课件
操作系统·系统级编程
小宇子2B3 天前
匿名页怎么回收:反向映射、swap entry、swap cache 和换入
操作系统
小宇子2B3 天前
区间树:反向映射的前置数据结构
操作系统
半条-咸鱼4 天前
【FreeRTOS】核心原理与实战速查手册
c语言·操作系统·rtos
花花无缺4 天前
Windows 定时执行 Python 脚本方案
python·操作系统·命令行
小宇子2B4 天前
LRU 不只是最近最少使用:active/inactive、anon/file、folio 和分代 LRU
操作系统
凉、介5 天前
Linux 设备驱动匹配机制
linux·笔记·单片机·学习·操作系统·嵌入式