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);
}
相关推荐
REDcker15 小时前
软件开发者需要关注CPU指令集差异吗?
linux·c++·操作系统·c·cpu·指令集·加密算法
技术小甜甜20 小时前
[电脑疑难档案] WSL 无法连接 MySQL 的解决方案:127.0.0.1 不管用?试试这个方法!
操作系统·开发·wsl
不穿格子的程序员1 天前
操作系统篇3——深入理解操作系统:Linux 常用命令、系统中断与用户态/内核态详解
linux·服务器·操作系统·内核态·用户态·中断
海棠蚀omo1 天前
Linux信号保存的核心:未决信号集与阻塞信号集——探秘内核如何实现信号的阻塞、暂存与派发
linux·操作系统
不穿格子的程序员1 天前
操作系统篇4——深入理解操作系统:僵尸进程、孤儿进程与进程调度算法详解
操作系统·僵尸进程·孤儿进程·进程调度
代码AC不AC2 天前
【Linux】计算机的基石:从冯·诺依曼体系结构到操作系统管理
linux·操作系统·冯诺依曼体系结构
序属秋秋秋3 天前
《Linux系统编程之进程环境》【环境变量】
linux·运维·服务器·c语言·c++·操作系统·系统编程
阿巴~阿巴~3 天前
自定义协议设计与实践:从协议必要性到JSON流式处理
服务器·网络·网络协议·json·操作系统·自定义协议
海棠蚀omo5 天前
解读Linux进程的“摩尔斯电码”:信号产生的原理与实践,掌控进程的生死时速
linux·操作系统
ZhengEnCi8 天前
P3H0-Python-os模块完全指南-操作系统接口与文件路径处理利器
python·操作系统