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);
}
相关推荐
报错小能手15 小时前
深入理解 Linux 物理内存管理
学习·操作系统
请输入蚊子1 天前
《操作系统真象还原》 第九章 线程
linux·操作系统·bochs·操作系统真像还原
small_wh1te_coder1 天前
拷打字节技术总监: 详解c语言嵌入式多线程编程中的头文件 #总结 上下篇合 #
c语言·开发语言·算法·操作系统·嵌入式
OpenAnolis小助手1 天前
极速、稳定、丝滑:OpenClaw 接入 Mooncake 后的性能跃迁
操作系统·龙蜥社区·大模型应用·mooncake·sglang·openclaw
散1121 天前
03操作系统-操作系统概览和硬件视角(上)
操作系统
OpenAnolis小助手1 天前
玄铁 C950 发布!龙蜥社区加速 RISC-V 云计算落地
云计算·操作系统·龙蜥社区·risc-v
代码小书生2 天前
Windows11 26H1 游戏定制优化版!6个版本:Win11 26H1专业版、专业工作站版,支持游戏、办公使用,电脑系统!
操作系统·电脑·系统·系统安装·电脑系统·windows11·重装系统
haaaaaaarry2 天前
【操作系统】第三章 内存管理(一)
linux·考研·操作系统
-森屿安年-2 天前
Linux - 进程
linux·操作系统
mifengxing2 天前
操作系统(三)
操作系统·多线程·os·进程信息传递