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);
}
相关推荐
阿昭L16 小时前
内存交换空间
操作系统·分页机制
阿昭L20 小时前
Windows内存管理中的交换空间
windows·操作系统·分页机制
_OP_CHEN20 小时前
【Linux系统编程】(三十六)深挖信号保存机制:未决、阻塞与信号集的底层实现全解析
linux·运维·操作系统·进程·c/c++·信号·信号保存
小李独爱秋21 小时前
模拟面试:lvs常见的工作模式有哪些?各有什么特点?
linux·运维·面试·职场和发展·操作系统·职场发展·lvs
小李独爱秋2 天前
模拟面试:不能关机的情况下 , 如果挂载目录卸载不掉应该怎么办?
linux·运维·面试·职场和发展·操作系统·文件系统
锅包一切2 天前
一、什么是Linux?
linux·运维·服务器·操作系统
BHXDML2 天前
操作系统实验:(七)动态分区分配方式的模拟
开发语言·数据库·操作系统
MR_Promethus2 天前
OS 操作系统 学习笔记
操作系统
Trouvaille ~2 天前
【Linux】高并发服务器的起点:五种 IO 模型与非阻塞 IO 本质解析
linux·运维·服务器·c++·操作系统·io模型·同步异步
_OP_CHEN2 天前
【Linux系统编程】(三十五)揭秘 Linux 信号产生:从终端到内核全解析
linux·运维·操作系统·进程·c/c++·信号·信号产生