pipe 使用问题

◐_◑ 2015-12-02 02:30:07
最近在学习管道,代码如下
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#define K 1024
#define writelen (12*K)
int main(){
int result = -1;
int fd[2],nbytes;
char string [writelen] = "你好,管道~!";
char readbuffer[10*K];
int * write_fd = &fd[1];
int * read_fd = &fd[0];

result = pipe(fd);
if(-1 == result){
printf("管道建立失败~!\n");
return -1;
}
int pid = fork();
if( -1 == pid ){
printf("fork 进程失败\n");
return -1;
}
if(0 == pid){
int write_size = writelen;
printf("pid[%d] write_size is [%d]i\n",getpid(),write_size);
result = 0;
close(*read_fd);
while(write_size > 0){
result = write(*write_fd,string,write_size);
printf("pid[%d] result is [%d]i\n",getpid(),result);
if(result > 0){
write_size -= result;
printf("pid[%d] 写入 %d 个数据, 剩余 %d 个数据\n",getpid(), result, write_size);
} else {
printf("pid[%d] sleep ----\n",getpid());
sleep(10);
}
}
printf("pid[%d] : 退出 \n",getpid());
return 0;
} else {
close(*write_fd);
printf("pid[%d] i---------------------\n",getpid());
while(1) {
printf("pid[%d] i---------------------\n",getpid());
nbytes = read(*read_fd,readbuffer,sizeof(readbuffer));
if(nbytes <= 0){
printf("pid[%d] 没有数据写入 \n",getpid());
break;
}
printf("pid[%d] : 接收到%d个数据,内容为:\"%s\" \n",getpid(),nbytes,readbuffer);
}
printf("pid[%d] : 退出 \n",getpid());
return 0;
}
return 0;
}


运行结果如下:
pid[3502] i---------------------
pid[3502] i---------------------
pid[3503] write_size is [12288]i
pid[3502] : 接收到10240个数据,内容为:"你好,管道~!"
pid[3502] i---------------------
pid[3502] : 接收到2048个数据,内容为:""
pid[3502] i---------------------
pid[3503] result is [12288]i
pid[3503] 写入 12288 个数据, 剩余 0 个数据
pid[3503] : 退出
pid[3502] 没有数据写入
pid[3502] : 退出

问题是 我不知道 为什么 代码中 需要 close 操作,我试着把 close 代码 注释掉 运行结果如下:

pid[3504] i---------------------
pid[3504] i---------------------
pid[3505] write_size is [12288]i
pid[3504] : 接收到10240个数据,内容为:"你好,管道~!"
pid[3504] i---------------------
pid[3504] : 接收到2048个数据,内容为:""
pid[3504] i---------------------
pid[3505] result is [12288]i
pid[3505] 写入 12288 个数据, 剩余 0 个数据
pid[3505] : 退出

然后 到这是就阻塞等待了, 有哪位大神 可以帮小弟解答一下啊,感激不尽,谢谢了~!
...全文
270 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
nswcfd 2015-12-04
  • 打赏
  • 举报
回复
pipe/fifo的EOF在内核里是由引用计数决定的,只有当最后一个write ref close之后,后续的read才会返回EOF。
chehw_1 2015-12-02
  • 打赏
  • 举报
回复
引用
the EOF will never be returned if the unnecessary ends of the pipe are not explicitly closed.
如果你不关闭所在进程中不使用的fd,比如父进程中没有关闭read_fd,那么子进程 nBytes = read(read_fd,...) 读不到EOF状态,会阻塞在等待读取中...

23,216

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧