其他分享
首页 > 其他分享> > xv6——文件系统:管道机制

xv6——文件系统:管道机制

作者:互联网

目录


作者:殷某人
更新时间:2022/07/10

管道机制

管道可以看到双端队列,一头读,一头写,如下图所示:

在xv6系统中,使用一块内存缓存块实现管道机制:

管道可以看作为特殊的文件, 通过文件的api对管道进行读写操作, 通过下面文件结构定义就可以看出来:

struct file {
  enum { FD_NONE, FD_PIPE, FD_INODE } type;
  int ref;
  char readable;
  char writable;
  struct pipe *pipe;   // 文件类型为管道时,对应的pipe。
  struct inode *ip;
  uint off;
};

数据结构定义

pipe的结构


struct pipe {
  struct spinlock lock;
  char data[PIPESIZE];
  uint nread;     // number of bytes read, 等价于下一个要读取的位置。注意,类型为无符号类型,达到最大值时自动反转。
  uint nwrite;    // number of bytes written, 等价于下一下要写入的位置。类型为无符号类型。
  int readopen;   // read fd is still open, 读该管道的进程数
  int writeopen;  // write fd is still open, 写该管道的进程数
};

函数实现

申请创建一个管道


int
pipealloc(struct file **f0, struct file **f1)
{
  struct pipe *p;

  p = 0;
  *f0 = *f1 = 0;
  if((*f0 = filealloc()) == 0 || (*f1 = filealloc()) == 0)
    goto bad;
  if((p = (struct pipe*)kalloc()) == 0)
    goto bad;
  p->readopen = 1;
  p->writeopen = 1;
  p->nwrite = 0;
  p->nread = 0;
  initlock(&p->lock, "pipe");
  (*f0)->type = FD_PIPE;
  (*f0)->readable = 1;
  (*f0)->writable = 0;
  (*f0)->pipe = p;
  (*f1)->type = FD_PIPE;
  (*f1)->readable = 0;
  (*f1)->writable = 1;
  (*f1)->pipe = p;
  return 0;

//PAGEBREAK: 20
 bad:
  if(p)
    kfree((char*)p);
  if(*f0)
    fileclose(*f0);
  if(*f1)
    fileclose(*f1);
  return -1;
}

关闭管道的读端/写端

void
pipeclose(struct pipe *p, int writable)
{
  acquire(&p->lock);
  if(writable){
    p->writeopen = 0;
    wakeup(&p->nread);
  } else {
    p->readopen = 0;
    wakeup(&p->nwrite);
  }
  if(p->readopen == 0 && p->writeopen == 0){
    release(&p->lock);
    kfree((char*)p);
  } else
    release(&p->lock);
}

读管道操作

int
piperead(struct pipe *p, char *addr, int n)
{
  int i;

  acquire(&p->lock);
  while(p->nread == p->nwrite && p->writeopen){  //DOC: pipe-empty
    if(myproc()->killed){
      release(&p->lock);
      return -1;
    }
    sleep(&p->nread, &p->lock); //DOC: piperead-sleep
  }
  for(i = 0; i < n; i++){  //DOC: piperead-copy
    if(p->nread == p->nwrite)
      break;
    addr[i] = p->data[p->nread++ % PIPESIZE];
  }
  wakeup(&p->nwrite);  //DOC: piperead-wakeup
  release(&p->lock);
  return i;
}

写管道操作

int
pipewrite(struct pipe *p, char *addr, int n)
{
  int i;

  acquire(&p->lock);
  for(i = 0; i < n; i++){
    while(p->nwrite == p->nread + PIPESIZE){  //DOC: pipewrite-full
      if(p->readopen == 0 || myproc()->killed){
        release(&p->lock);
        return -1;
      }
      wakeup(&p->nread);
      sleep(&p->nwrite, &p->lock);  //DOC: pipewrite-sleep
    }
    p->data[p->nwrite++ % PIPESIZE] = addr[i];
  }
  wakeup(&p->nread);  //DOC: pipewrite-wakeup1
  release(&p->lock);
  return n;
}

标签:struct,lock,文件系统,xv6,pipe,nwrite,管道,nread
来源: https://www.cnblogs.com/yinheyi/p/16464420.html