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);
}
相关推荐
mifengxing1 天前
操作系统(四)
linux·服务器·网络·操作系统
暴力求解2 天前
Linux---保存信号
linux·运维·服务器·开发语言·操作系统
苦 涩6 天前
考研408笔记之操作系统(五)——输入输出(IO)管理
笔记·操作系统·考研408
苦 涩6 天前
考研408笔记之操作系统(四)——文件管理
笔记·操作系统·考研408
shy^-^cky7 天前
文件的逻辑结构+ 物理结构
数据结构·操作系统·文件·数据·逻辑结构·物理结构·文件结构
苦 涩7 天前
考研408笔记之操作系统(三)——内存管理
笔记·操作系统·考研408
苦 涩7 天前
考研408笔记之操作系统(二)——进程与线程
笔记·操作系统·考研408
苦 涩7 天前
考研408笔记之操作系统(一)——计算机系统概述
笔记·操作系统·考研408
a里啊里啊9 天前
软考-软件评测师:知识点整理(二)——操作系统基础知识
操作系统·线程·进程·软考·pv操作·软件评测师
W.W.H.11 天前
FreeRTOS移植(保姆级教程)
经验分享·单片机·操作系统·freertos·rtos