首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

进程间通信-关于管道,该如何处理

2012-07-31 
进程间通信---关于管道C/C++ code1 #includestdio.h2 #includeunistd.h3 #includestdlib.h45 int ma

进程间通信---关于管道

C/C++ code
1 #include<stdio.h>2 #include<unistd.h>3 #include<stdlib.h>45 int main()6 {7     int n;8     pid_t pid;9     int fd[2];10     char line[56];11     if(pipe(fd) < 0)12     {13         printf("pipe error\n");14     }15     if((pid = fork()) > 0){16         close(fd[1]);17         n = read(fd[0],line,56);18         if(n > 0){19             printf("%s\n",line);20         }21     }else if(pid == 0){22         dup2(fd[1],1);23         close(fd[1]);24         close(fd[0]);25         int x = 20;26         while(x){27             printf("hello world\n");28             x--;29             sleep(1);30         }31         return 0;32     }33     return 0;34 }35

以上代码,没问题,如果我把子进程里的 x-- 去掉,父进程就会一直阻塞,请问为什么?因为子进程执行不完的原因吗?父进程没有从管道读取56个字符码?为什么没输出来?

[解决办法]
感觉是标准IO库写pipe时是全缓存的....
子进程会一直到最后全写完发会真正发送到pipe的读端
你可以在子进程里加fflush(stdout)看一下

热点排行