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);
}
相关推荐
丐中丐99912 小时前
Android系统中如何在Native层调用java实现的系统服务
android·操作系统
丐中丐99912 小时前
在Android中利用抽象类对外提供系统接口
android·操作系统
我命由我123451 天前
Windows 操作系统 - Windows 设置始终使用 Windows 照片查看器打开图片
运维·windows·经验分享·笔记·学习·操作系统·运维开发
huangyuchi.2 天前
【Linux】环境变量
linux·运维·操作系统·环境变量·系统调用·命令行参数·main函数参数
pedestrian_h2 天前
操作系统-lecture5(线程)
操作系统·线程·进程
Jooolin2 天前
【Linux】指令大全!常用的都在这了~
linux·操作系统·ai编程
自由鬼4 天前
如何处理Y2K38问题
java·运维·服务器·程序人生·安全·操作系统
moning4 天前
Window 的 Type 失效了?IME 为什么在 Toast 下方?
前端·操作系统·android studio
自由鬼4 天前
AI赋能操作系统:通往智能运维的未来
linux·运维·服务器·人工智能·程序人生·ai·操作系统
Tjyuking4 天前
OS架构整理
运维·c++·缓存·架构·操作系统