+ -
当前位置:首页 → 问答吧 → 管道的写阻塞问题!

管道的写阻塞问题!

时间:2010-08-18

来源:互联网

请问对一个管道写时,如果管道缓冲区不够,是不是会阻塞?
如果是的话,那么下面这个程序运行的时候,为什么一开始立马就打印了5000?而不是等读进程读取后再写?
如果不是,那么关于管道写数据时的阻塞问题,正解是什么?
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <sys/types.h>
  5. #include <unistd.h>

  6. //PIPE_BUF = 4096
  7. int main()
  8. {
  9.         int fd[2];
  10.         int ret,request;
  11.         char rbuf[4096];
  12.         char wbuf[4096*2];
  13.         char *msg="hello,pipe!",*msg2="hello,I come here ,too!";
  14.         pid_t pid;
  15.         int stat_val;

  16.         if(pipe(fd)<0)
  17.         {
  18.                 printf("pipe error\n");
  19.                 exit(1);
  20.         }

  21.         if((pid=fork())==0)
  22.         {
  23.                 //child process write
  24.                 close(fd[0]);
  25.                 ret=write(fd[1],wbuf,1024);
  26.                 printf("I am writer and I write %d Byte data\n",ret);
  27.                 ret=write(fd[1],wbuf,5000);
  28.                 printf("I am writer and I write %d Byte data\n",ret);
  29.                 printf("writer has over\n");
  30.                 close(fd[1]);
  31.                 exit(0);
  32.         }
  33.         else if(pid>0)
  34.         {
  35.                 //parent process read
  36.                 close(fd[1]);
  37.                 sleep(5);
  38.                 while(1)
  39.                 {
  40.                         sleep(1);
  41.                         ret=read(fd[0],rbuf,1000);
  42.                         printf("I am reader and the num of reading data is %d\n",ret);
  43.                 }
  44.                 close(fd[0]);
  45.                 exit(0);
  46.         }
  47. }
复制代码

作者: edsionte   发布时间: 2010-08-18



QUOTE:
请问对一个管道写时,如果管道缓冲区不够,是不是会阻塞?
如果是的话,那么下面这个程序运行的时候,为什 ...
edsionte 发表于 2010-08-18 23:11




有问题?


QUOTE:
I am writer and I write 1024 Byte data
I am writer and I write 5000 Byte data
writer has over
I am reader and the num of reading data is 1000
I am reader and the num of reading data is 1000
I am reader and the num of reading data is 1000
I am reader and the num of reading data is 1000
I am reader and the num of reading data is 1000
I am reader and the num of reading data is 1000
I am reader and the num of reading data is 24
I am reader and the num of reading data is 0
I am reader and the num of reading data is 0
I am reader and the num of reading data is 0

作者: 叶叶叶Yeah   发布时间: 2010-08-19

回复 edsionte


     是的,上一个帖子我已经说过了。你知道你这里的pipe大小是多少?(大小是 PIPE_SIZE,在内核中定义)man7 pipe好好看看再说

作者: churchmice   发布时间: 2010-08-19

热门下载

更多