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);
}
相关推荐
ZhengEnCi5 小时前
O06-缺页中断与一般中断的主要区别
操作系统
ZhengEnCi6 小时前
O05-分时操作系统和实时操作系统区别
操作系统
z200509301 天前
【linux学习】深入理解linux文件I/O,从C标准库到内核态
linux·学习·操作系统
量子炒饭大师1 天前
【Linux系统编程:进程概念】——【从 冯诺依曼系统体系结构 到 操作系统】
linux·运维·服务器·操作系统·冯诺依曼
带娃的IT创业者1 天前
数字考古学:当整个操作系统史被装进一个浏览器
操作系统·前端开发·webassembly·虚拟化技术·数字考古学·windows 95·复古计算
暴力求解2 天前
Mysql数据库基础
数据库·mysql·操作系统
用户887665426632 天前
Linux 终端入门:新手必须掌握的常用命令和基本思路
前端·操作系统
atomicmaker4 天前
操作系统 — 内存管理
操作系统·内存管理·虚拟内存·段页式
atomicmaker4 天前
操作系统 — 文件管理
操作系统·文件管理·文件系统·计算机系统
白狐_7984 天前
【XV6操作系统】Lab2(Page Table) 满分通关与答辩指南:结合408考点深度剖析
操作系统·麒麟·xv6