zoukankan      html  css  js  c++  java
  • linux内核情景分析之匿名管道

    管道的机制由pipe()创建,由pipe()所建立的管道两端都在同一进程.所以必须在fork的配合下,才可以在具有亲缘关系的进程通信
    1. /*
    2. * sys_pipe() is the normal C calling standard for creating
    3. * a pipe. It's not the way Unix traditionally does this, though.
    4. */
    5. asmlinkage int sys_pipe(unsigned long * fildes)
    6. {
    7. int fd[2];//fd表示,一个读,一个写
    8. int error;
    9. error = do_pipe(fd);
    10. if (!error) {
    11. if (copy_to_user(fildes, fd, 2*sizeof(int)))//从内核态拷贝到用户态
    12. error = -EFAULT;
    13. }
    14. return error;
    15. }
     sys_pipe()主体是调用do_pipe()
    1. int do_pipe(int *fd)
    2. {
    3. struct qstr this;
    4. char name[32];//目录项名字
    5. struct dentry *dentry;//目录结构
    6. struct inode * inode;//inode对应一个管道,不过管道无实际存储,不在硬盘也不在文件系统
    7. struct file *f1, *f2;//父子进程操作管道对应的文件对象
    8. int error;
    9. int i,j;
    10. error = -ENFILE;
    11. f1 = get_empty_filp();//获取一个file对象,因为管道在不同的进程,两端不可以共享一个file
    12. if (!f1)
    13. goto no_files;
    14. f2 = get_empty_filp();//获取1个file对象,同上
    15. if (!f2)
    16. goto close_f1;
    17. inode = get_pipe_inode();//获取一个inode用于表示管道这个无形文件,分配缓存,初始化
    18. if (!inode)
    19. goto close_f12;
    20. error = get_unused_fd();//获取一个fd用于绑定file对象
    21. if (error < 0)
    22. goto close_f12_inode;
    23. i = error;
    24. error = get_unused_fd();//同上
    25. if (error < 0)
    26. goto close_f12_inode_i;
    27. j = error;
    28. error = -ENOMEM;
    29. sprintf(name, "[%lu]", inode->i_ino);//操作
    30. this.name = name;
    31. this.len = strlen(name);
    32. this.hash = inode->i_ino; /* will go */
    33. dentry = d_alloc(pipe_mnt->mnt_sb->s_root, &this);//分配一个目录,因为file无直接指向inode.file只能通过指向目录的指针指向目录项中转找到inode
    34. if (!dentry)
    35. goto close_f12_inode_i_j;
    36. dentry->d_op = &pipefs_dentry_operations;
    37. d_add(dentry, inode);//将目录与inode挂钩
    38. f1->f_vfsmnt = f2->f_vfsmnt = mntget(mntget(pipe_mnt));//挂载到vfs
    39. f1->f_dentry = f2->f_dentry = dget(dentry);//设置file对象的指向目录指针
    40. /*设置只读属性, read file */
    41. f1->f_pos = f2->f_pos = 0;
    42. f1->f_flags = O_RDONLY;//设置只读属性
    43. f1->f_op = &read_pipe_fops;//设置f1的读管道指针操作
    44. f1->f_mode = 1;
    45. f1->f_version = 0;
    46. /* 写文件相关对象,只写数学,操作为write_pipe_fopswrite file */
    47. f2->f_flags = O_WRONLY;//设置只可写属性
    48. f2->f_op = &write_pipe_fops;//设置写操作
    49. f2->f_mode = 2;
    50. f2->f_version = 0;
    51. fd_install(i, f1);//fd与file对象绑定
    52. fd_install(j, f2);//fd与file对象绑定
    53. fd[0] = i;
    54. fd[1] = j;
    55. return 0;
    56. close_f12_inode_i_j:
    57. put_unused_fd(j);
    58. close_f12_inode_i:
    59. put_unused_fd(i);
    60. close_f12_inode:
    61. free_page((unsigned long) PIPE_BASE(*inode));
    62. kfree(inode->i_pipe);
    63. inode->i_pipe = NULL;
    64. iput(inode);
    65. close_f12:
    66. put_filp(f2);
    67. close_f1:
    68. put_filp(f1);
    69. no_files:
    70. return error;
    71. }
    接下来查看下get_pipe_inode()表示inode对应的文件管道,我们对于inode先关心下第一个成分i_pipe指向一个pipe_inode_info,只有inode表示为一个管道才使用,否则一般文件将此位设置为NULL
    1. struct pipe_inode_info {
    2. wait_queue_head_t wait;//等待队列
    3. char *base;//用于指向一页的缓冲区
    4. unsigned int start;
    5. unsigned int readers;//读的个数
    6. unsigned int writers;//写的个数
    7. unsigned int waiting_readers;//等待读的个数
    8. unsigned int waiting_writers;//等待写的个数
    9. unsigned int r_counter;//读的次数
    10. unsigned int w_counter;//写的次数
    11. };
    另外还是用一些宏定义,用来设置i_pipe结构
    1. #define PIPE_SEM(inode) (&(inode).i_sem)//inode信号量
    2. #define PIPE_WAIT(inode) (&(inode).i_pipe->wait)//inode的i_pipe的管道等待队列
    3. #define PIPE_BASE(inode) ((inode).i_pipe->base)//inode管道的base缓冲区指针
    4. #define PIPE_START(inode) ((inode).i_pipe->start)//管道的起始地址
    5. #define PIPE_LEN(inode) ((inode).i_size)//管道剩余数据
    6. #define PIPE_READERS(inode) ((inode).i_pipe->readers)//管道读的对象个数
    7. #define PIPE_WRITERS(inode) ((inode).i_pipe->writers)//管道写的对象个数
    8. #define PIPE_WAITING_READERS(inode) ((inode).i_pipe->waiting_readers)//管道等待的对象个数
    9. #define PIPE_WAITING_WRITERS(inode) ((inode).i_pipe->waiting_writers)
    10. #define PIPE_RCOUNTER(inode) ((inode).i_pipe->r_counter)
    11. #define PIPE_WCOUNTER(inode) ((inode).i_pipe->w_counter)
    12. #define PIPE_EMPTY(inode) (PIPE_LEN(inode) == 0)//管道是否为空
    13. #define PIPE_FULL(inode) (PIPE_LEN(inode) == PIPE_SIZE)//管道是否满了
    14. #define PIPE_FREE(inode) (PIPE_SIZE - PIPE_LEN(inode))//管道剩余空间
    15. #define PIPE_END(inode) ((PIPE_START(inode) + PIPE_LEN(inode)) & (PIPE_SIZE-1))
    16. #define PIPE_MAX_RCHUNK(inode) (PIPE_SIZE - PIPE_START(inode))
    17. #define PIPE_MAX_WCHUNK(inode) (PIPE_SIZE - PIPE_END(inode))


    1. static struct inode * get_pipe_inode(void)
    2. {
    3. struct inode *inode = get_empty_inode();//分配一空的inode节点
    4. //inode第一个成分i_pipe指向一个pipe_inode_info,只有inode表示为一个管道才使用
    5. if (!inode)
    6. goto fail_inode;
    7. if(!pipe_new(inode))//分配缓冲区,以及i_ipipe结构初始化
    8. goto fail_iput;
    9. PIPE_READERS(*inode) = PIPE_WRITERS(*inode) = 1;//设置write
    10. inode->i_fop = &rdwr_pipe_fops;//设置管道相关读写操作
    11. inode->i_sb = pipe_mnt->mnt_sb;
    12. /*
    13. * Mark the inode dirty from the very beginning,
    14. * that way it will never be moved to the dirty
    15. * list because "mark_inode_dirty()" will think
    16. * that it already _is_ on the dirty list.
    17. */
    18. inode->i_state = I_DIRTY;
    19. inode->i_mode = S_IFIFO | S_IRUSR | S_IWUSR;
    20. inode->i_uid = current->fsuid;
    21. inode->i_gid = current->fsgid;
    22. inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
    23. inode->i_blksize = PAGE_SIZE;
    24. return inode;
    25. fail_iput:
    26. iput(inode);
    27. fail_inode:
    28. return NULL;
    29. }
    用于管道相关操作函数指针,值得注意的是代码并没有设置inode结构中的inode_operaions结构指针i_op.所以该指针为0,对于用于实现管道的inode并不允许对这里的inode进行常规操作,只有当inode代表有形文件才可以使用
    1. struct file_operations rdwr_pipe_fops = {
    2. llseek: pipe_lseek,
    3. read: pipe_read,
    4. write: pipe_write,
    5. poll: pipe_poll,
    6. ioctl: pipe_ioctl,
    7. open: pipe_rdwr_open,
    8. release: pipe_rdwr_release,
    9. };

    1. struct inode* pipe_new(struct inode* inode)
    2. {
    3. unsigned long page;
    4. page = __get_free_page(GFP_USER);//获取一页用作管道的缓冲区
    5. if (!page)
    6. return NULL;
    7. //再分配一缓冲区用作pipe_inode_info数据结构
    8. inode->i_pipe = kmalloc(sizeof(struct pipe_inode_info), GFP_KERNEL);
    9. if (!inode->i_pipe)
    10. goto fail_page;
    11. init_waitqueue_head(PIPE_WAIT(*inode));//初始化倒艿廊待队列
    12. PIPE_BASE(*inode) = (char*) page;//指向缓冲区
    13. PIPE_START(*inode) = PIPE_LEN(*inode) = 0;//长度与起始地址
    14. PIPE_READERS(*inode) = PIPE_WRITERS(*inode) = 0;//设置为0
    15. PIPE_WAITING_READERS(*inode) = PIPE_WAITING_WRITERS(*inode) = 0;//等待读写数目设置为0
    16. PIPE_RCOUNTER(*inode) = PIPE_WCOUNTER(*inode) = 1;//计数设置为1
    17. return inode;
    18. fail_page:
    19. free_page(page);
    20. return NULL;
    21. }
    fd1绑定的read_pipe_fops的写操作为bad_pipe_w,如果fd1使用了写操作,那么将返回错误,fd2的write_pipe_fops一样.以下就不举例了
    1. struct file_operations read_pipe_fops = {
    2. llseek: pipe_lseek,
    3. read: pipe_read,
    4. write: bad_pipe_w,
    5. poll: pipe_poll,
    6. ioctl: pipe_ioctl,
    7. open: pipe_read_open,
    8. release: pipe_read_release,
    9. };
    前面inode将结构中的i_fop指针设置为rdwr_pipe_fops,那是双向,而对于代表管道两端的两个已打开文件来说,一个只可写,一个只可读.一般来说file结构的指针f_op只来自inode的i_fop都指向同一个file_operations结构,而这里对于管道这么一种特殊的文件,则使得管道两端的file结构各自指向不同的file_operation,以此确保一端只可写,一端只可读,管道只是一种特殊的文件不属于特定的文件系统,而自己构成一种独立的文件系统,也有自身的数据结构pipe_fs_type

    接下来查看有关关闭管道函数
    pipe_read_release与pipe_write_release
    1. static int
    2. pipe_read_release(struct inode *inode, struct file *filp)
    3. {
    4. return pipe_release(inode, 1, 0);//1表示读的相关描述符减1,因为关闭,写端设置为0
    5. }
    1. static int
    2. pipe_write_release(struct inode *inode, struct file *filp)
    3. {
    4. return pipe_release(inode, 0, 1);
    5. }
    上面2个函数的主体部分是pipe_release
    1. static int
    2. pipe_release(struct inode *inode, int decr, int decw)
    3. {
    4. down(PIPE_SEM(*inode));
    5. PIPE_READERS(*inode) -= decr;//共享计数-decr
    6. PIPE_WRITERS(*inode) -= decw;//共享计数-decw
    7. if (!PIPE_READERS(*inode) && !PIPE_WRITERS(*inode)) {//如果读端跟写端的相关fd都关闭了
    8. struct pipe_inode_info *info = inode->i_pipe;
    9. inode->i_pipe = NULL;//
    10. free_page((unsigned long) info->base);//将页面释放
    11. kfree(info);//将inode释放
    12. } else {
    13. wake_up_interruptible(PIPE_WAIT(*inode));
    14. }
    15. up(PIPE_SEM(*inode));
    16. return 0;
    17. }


    接下来看管道特有的读写操作
    pipe_read操作
    1. static ssize_t
    2. pipe_read(struct file *filp, char *buf, size_t count, loff_t *ppos)
    3. {
    4. struct inode *inode = filp->f_dentry->d_inode;//获取inode
    5. ssize_t size, read, ret;
    6. //不允许seek操作
    7. /* Seeks are not allowed on pipes. */
    8. ret = -ESPIPE;
    9. read = 0;
    10. if (ppos != &filp->f_pos)//ppos必须指向filp->f_pos
    11. goto out_nolock;
    12. /* Always return 0 on null read. */
    13. ret = 0;
    14. if (count == 0)
    15. goto out_nolock;
    16. /* Get the pipe semaphore */
    17. ret = -ERESTARTSYS;
    18. if (down_interruptible(PIPE_SEM(*inode)))
    19. goto out_nolock;
    20. if (PIPE_EMPTY(*inode)) {//管道中的字节数如果等于0,表示为空管道
    21. do_more_read:
    22. ret = 0;
    23. if (!PIPE_WRITERS(*inode))//如果管道无人写,那就等于写端关闭,那么客户端也要关闭
    24. goto out;
    25. ret = -EAGAIN;
    26. if (filp->f_flags & O_NONBLOCK)//设置非阻塞直接返回,因为管道为空
    27. goto out;
    28. for (;;) {
    29. PIPE_WAITING_READERS(*inode)++;
    30. pipe_wait(inode);//休眠,因为没有数据可读
    31. PIPE_WAITING_READERS(*inode)--;
    32. ret = -ERESTARTSYS;
    33. if (signal_pending(current))//当前进程有信号未处理
    34. goto out;
    35. ret = 0;
    36. if (!PIPE_EMPTY(*inode))//如果管道不为空,跳出这循环
    37. break;
    38. if (!PIPE_WRITERS(*inode))//没有写端,直接跳出
    39. goto out;
    40. }
    41. }
    42. /* Read what data is available. */
    43. ret = -EFAULT; //如果读取
    44. //count表示剩余数不为0,并且pipe还有数据
    45. while (count > 0 && (size = PIPE_LEN(*inode))) {
    46. char *pipebuf = PIPE_BASE(*inode) + PIPE_START(*inode);//起始位置
    47. ssize_t chars = PIPE_MAX_RCHUNK(*inode);//start到base
    48. if (chars > count)//如果start到base的数据大于count
    49. chars = count;
    50. if (chars > size)//
    51. chars = size;
    52. //有3种情况.(1)读取到要求长度,刚好或者还有剩余,直接返回要求长度,否则返回实际长度
    53. if (copy_to_user(buf, pipebuf, chars))
    54. goto out;
    55. read += chars;//read等于实际读取长度
    56. PIPE_START(*inode) += chars;//起始位置更改
    57. PIPE_START(*inode) &= (PIPE_SIZE - 1);//对齐
    58. PIPE_LEN(*inode) -= chars;//长度更爱
    59. count -= chars;//要求长度-chars长度
    60. buf += chars;//用户缓冲+chars
    61. }
    62. /* Cache behaviour optimization */
    63. if (!PIPE_LEN(*inode))//如果长度为0,就把start设置到页开头
    64. PIPE_START(*inode) = 0;
    65. //如果读取的数据不够要求的长度并且还有等待写进程并且未设置阻塞
    66. if (count && PIPE_WAITING_WRITERS(*inode) && !(filp->f_flags & O_NONBLOCK)) {
    67. /*
    68. * We know that we are going to sleep: signal
    69. * writers synchronously that there is more
    70. * room.
    71. */
    72. wake_up_interruptible_sync(PIPE_WAIT(*inode));//唤醒
    73. if (!PIPE_EMPTY(*inode))//管道必须为空
    74. BUG();
    75. goto do_more_read;//继续读
    76. }
    77. /* Signal writers asynchronously that there is more room. */
    78. wake_up_interruptible(PIPE_WAIT(*inode));
    79. ret = read;
    80. out:
    81. up(PIPE_SEM(*inode));
    82. out_nolock:
    83. if (read)
    84. ret = read;
    85. return ret;
    86. }
    管道读操作:(管道为空)管道不允许seek操作,
    1.管道如果为空但通过pipe_writers判断,没有写的file对象那就直接返回
    2.管道为空并且设置了非阻塞,直接返回
    3.管道数据为空,但有相关fd会进行写操作.休眠等待被唤醒读取数据
    4.管道不为空,有3种情况,管道读取到了要求长度,刚好为空或者有剩余,直接返回
    5.管道读取的数据没有达到要求,,并且设置了非阻塞,那就读多少返回多少
    5.如果管道读取的数据没达到要求(读取数据大于剩余数据),并且还有写fd在等待,并且没有设置非阻塞标志
    则唤醒写fd进程,继续循环读.直到读完或者file对象没了(数据还未达到要求).

    pipe_write操作
    1. static ssize_t
    2. pipe_write(struct file *filp, const char *buf, size_t count, loff_t *ppos)
    3. {
    4. struct inode *inode = filp->f_dentry->d_inode;//获取节点
    5. ssize_t free, written, ret;
    6. /* Seeks are not allowed on pipes. */
    7. ret = -ESPIPE;
    8. written = 0;
    9. if (ppos != &filp->f_pos)
    10. goto out_nolock;
    11. /* Null write succeeds. */
    12. ret = 0;
    13. if (count == 0)//写的数据要求为0,直接跳到out_nolock
    14. goto out_nolock;
    15. ret = -ERESTARTSYS;
    16. if (down_interruptible(PIPE_SEM(*inode)))//枷锁
    17. goto out_nolock;
    18. /* No readers yields SIGPIPE. */
    19. if (!PIPE_READERS(*inode))//如果没有读的fd了,直接发送sigpipe信号
    20. goto sigpipe;
    21. //是否超过缓冲区大小,超过设置为1
    22. /* If count <= PIPE_BUF, we have to make it atomic. */
    23. free = (count <= PIPE_BUF ? count : 1);
    24. /* Wait, or check for, available space. */
    25. if (filp->f_flags & O_NONBLOCK) {//表示即使读不到东西,也不该阻塞
    26. ret = -EAGAIN;
    27. //PIPE_SIZE - PIPE_LEN(inode)
    28. if (PIPE_FREE(*inode) < free)//管道剩余的空间小于要写入的数据,直接退出
    29. goto out;
    30. } else {
    31. while (PIPE_FREE(*inode) < free) {//如果要写入的字节数大于整个缓冲区的大小,那就睡眠
    32. PIPE_WAITING_WRITERS(*inode)++;//等待写++
    33. pipe_wait(inode);//睡眠
    34. PIPE_WAITING_WRITERS(*inode)--;
    35. ret = -ERESTARTSYS;
    36. if (signal_pending(current))//有信号要处理
    37. goto out;
    38. if (!PIPE_READERS(*inode))//如果不存在读的fd,发送sigpipe信号
    39. goto sigpipe;
    40. }
    41. }
    42. /* Copy into available space. */
    43. ret = -EFAULT;
    44. while (count > 0) {
    45. int space;
    46. char *pipebuf = PIPE_BASE(*inode) + PIPE_END(*inode);
    47. ssize_t chars = PIPE_MAX_WCHUNK(*inode);
    48. ////如果没有剩余空间了,那么就只说明,要写的字节大于缓冲区的总大小,执行下面的do_while循环
    49. if ((space = PIPE_FREE(*inode)) != 0) {//space获取剩余空间
    50. if (chars > count)
    51. chars = count;
    52. if (chars > space)
    53. chars = space;//space与count中选取最小的那个
    54. //拷贝到管道
    55. if (copy_from_user(pipebuf, buf, chars))
    56. goto out;
    57. written += chars;//写入多少数据
    58. PIPE_LEN(*inode) += chars;//长度++
    59. count -= chars;
    60. buf += chars;
    61. space = PIPE_FREE(*inode);
    62. continue;
    63. }
    64. //如果剩余空间等于0
    65. ret = written;
    66. if (filp->f_flags & O_NONBLOCK)
    67. break;
    68. do {
    69. /*
    70. * Synchronous wake-up: it knows that this process
    71. * is going to give up this CPU, so it doesnt have
    72. * to do idle reschedules.
    73. */
    74. wake_up_interruptible_sync(PIPE_WAIT(*inode));//唤醒等待的进程
    75. PIPE_WAITING_WRITERS(*inode)++;
    76. pipe_wait(inode);//睡眠等待
    77. PIPE_WAITING_WRITERS(*inode)--;
    78. if (signal_pending(current))//唤醒很可能是有信号
    79. goto out;
    80. if (!PIPE_READERS(*inode))//如果没inode读管道
    81. goto sigpipe;
    82. } while (!PIPE_FREE(*inode));//如果管道一直是满的,继续do_while循环,直到有剩余空间
    83. ret = -EFAULT;
    84. }
    85. /* Signal readers asynchronously that there is more data. */
    86. wake_up_interruptible(PIPE_WAIT(*inode));//唤醒等待读的进程
    87. inode->i_ctime = inode->i_mtime = CURRENT_TIME;
    88. mark_inode_dirty(inode);
    89. out:
    90. up(PIPE_SEM(*inode));
    91. out_nolock:
    92. if (written)
    93. ret = written;
    94. return ret;
    95. sigpipe://读端都关闭了,那就发送sigpipe信号
    96. if (written)
    97. goto out;
    98. up(PIPE_SEM(*inode));
    99. send_sig(SIGPIPE, current, 0);
    100. return -EPIPE;
    101. }

    管道写相关操作:(以下阻塞未默认设置)
    1.写入的数据参数为0,直接返回
    2.判断了管道没有读的fd,直接返回并发送SIGPIPE信号表示管道破裂
    3.是否超过了管道的缓存大小,超过了则不保证其原子性并将free设置为1,并将要读取的字节限制为一页大小,这时候能有多大空间就写多少
    字节,余下的等消费者度偶一些字节再继续写
    4.设置了不阻塞位,但管道剩余空间小于要写入空间直接退出
    5.如果要写入的字节大于整个缓冲区剩余空间,那当前写管道进程睡眠,直到缓冲区有剩余空间
    6.如果写入的字节数等于要求的字节数,那就返回

    在阻塞的情况下:
        · 如果write的字节数小于等于PIPE_BUF,那么write会阻塞到写入所有数据,并且 写入操作是原子的。
        ·  如果write的字节数大于PIPE_BUF,那么write会阻塞到写入所有数据,但写入操作不是原子的,即write会根据当前缓冲区剩余的大小,写入相应的字节数,然后等待下一次有空余的缓冲区,这中间可能会有其他进程进行write操作。

    在非阻塞的情况下:
        · 如果write的字节数小于等于PIPE_BUF,且管道或FIFO有足以存放要写入数据大小的空间,那么就写入所有数据;
        ·  如果write的字节数小于等于PIPE_BUF,且管道或FIFO没有足够存放要写入数据大小的空间,那么就会立即返回EAGAIN错误。
        · 如果write的字节数大于PIPE_BUF,且管道或FIFO有至少1B的空间,那么就内核就会写入相应的字节数,然后返回已写入的字节数;
        · 如果write的字节数大于PIPE_BUF,且管道或FIFO无任何的空间,那么就会立即返回EAGAIN错误。
















  • 相关阅读:
    20-存储过程
    21-事务
    18-触发器
    19-函数
    16-pymysql模块的使用
    17-视图
    CodeForces 1369B. AccurateLee
    CodeForces 1312D.Count the Arrays(组合数学)
    CodeForces 1362D. Johnny and Contribution
    CodeForces 1363F. Rotating Substrings
  • 原文地址:https://www.cnblogs.com/zengyiwen/p/6003103.html
Copyright © 2011-2022 走看看