关于实现操作系统中一些操作的注意事项【随时更新】

  总结一些最近做MIT.S081 OS遇到的一些问题

  1)在使用pipe时,应注意到对资源的释放问题,比如说在primes这个实验中遇到了当使用了pipe[1]对管道进行写入时,如果最后没有将pipe的写资源释放,可能导致资源持续被占用,进程无法正常结束的问题;

附上source code

#include "kernel/stat.h"
#include "kernel/types.h"
#include "user/user.h"

void sieve(int left[2]) 
{
    int thisnum;
    int right[2];
    close(left[1]);
    read(left[0], &thisnum, sizeof(thisnum));
    // printf("prime %d\n", thisnum);
    if(thisnum == -1) {
        close(left[0]);
        exit(0);    
    }
    printf("prime %d\n",thisnum);
    //err situation
    if(pipe(right) < 0) {
        printf("create right queue err\n");
        exit(-1);
    }
    int pid = fork();
    // printf("pid:%d\n",pid);
    if(pid < 0) {
        // printf("create child process err\n");
        close(right[1]);
        close(right[0]);
        close(left[0]);
        exit(-1);
    }
    //normal situation
    else if(pid == 0) {
        //child
        // printf("this is a child\n");
        close(right[1]);
        close(left[0]);
        sieve(right);   
    }
    else {
        //parent
        close(right[0]);
        int buffer = 0;
        while(read(left[0], &buffer, sizeof(buffer))) {
            if(buffer % thisnum) {
                write(right[1], &buffer, sizeof(buffer));
            }
        }
    }
    int buffer = -1;
    write(right[1], &buffer, sizeof(buffer));
    close(right[1]);
    close(left[0]);
    // close(left[1]);
    wait(0);
    exit(0);
}

void init(int q[2])
{
    for (int i = 2; i <= 35; ++i) {
        // printf("this num is:%d\n",i);
        write(q[1], &i, sizeof(i));
    }
    int temp = -1;
    write(q[1], &temp, sizeof(temp));
    sieve(q);
}

void create_pipe() 
{
    int que[2];
    if(pipe(que) < 0) {
        printf("create pipe err\n");
        exit(-1);
    }
    init(que);
    exit(0);
}

int main(int args, char *argv[]) 
{
    create_pipe();
    exit(0);
}
View Code

 

posted @ 2023-09-15 22:01  Orangeko  阅读(25)  评论(0编辑  收藏  举报