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);
}
相关推荐
我命由我123451 天前
Windows 操作系统 - 符号链接
linux·运维·windows·系统架构·操作系统·运维开发·系统
小肝一下1 天前
1.C++-⾼性能内存池
c++·操作系统·项目·高并发内存池·内存分割与利用
liang_jy2 天前
文件管理(八)—— 虚拟文件系统
面试·操作系统
liang_jy2 天前
文件管理(七)—— 文件系统的层次结构和布局
面试·操作系统
深信达沙箱2 天前
漏洞修不完、合规过不了?先御OS如何让嵌入式设备‘出厂即合规
arm开发·操作系统·嵌入式操作系统
小宇子2B2 天前
struct file 不是磁盘文件:一次打开实例和共享偏移
操作系统
liang_jy3 天前
文件管理(六)—— 文件共享和保护
面试·操作系统
liang_jy3 天前
文件管理(五)—— 文件的基本操作
面试·操作系统
小宇子2B3 天前
fd 只是数组下标:`ksys_write()` 怎么找到 `struct file`
操作系统
liang_jy4 天前
文件管理(四)—— 文件存储空间管理
面试·操作系统