实现进程间全双工通道的问题
时间:2010-07-24
来源:互联网
下面的代码是实现进程间的全双工通道。今天我在调试下面的代码的时候,遇到了这样一个问题,在child_rw_pipe函数中(parent_rw_piep函数也是如此)如果我先read,再write。程序运行时就会没反应。但是先write再read就可以正确运行处结果。麻烦大家分析一下为什么?
复制代码
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <unistd.h>
- #include <string.h>
-
- void child_rw_pipe(int readfd,int writefd)
- {
- char message1[100],*message2="The message was wrote to pipe2! Now you read it from pipe2.";
-
- printf("enter child\n");
- //child process write message to pipe2
- write(writefd,message2,strlen(message2)+1);
- //child process read message from pipe1
- read(readfd,message1,100);
- printf("read from pipe1:%s\n",message1);
- }
-
- void parent_rw_pipe(int readfd,int writefd)
- {
- char message2[100],*message1="The message was wrote to pipe1! Now you read it from pipe1.";
-
- printf("enter parent\n");
- //parent process write message to pipe1
- write(writefd,message1,strlen(message1)+1);
- //parent process read message from pipe2
- read(readfd,message2,100);
- printf("read from pipe2:%s\n",message2);
- }
-
- int main()
- {
- int fd1[2],fd2[2];
- pid_t pid;
- int stat_val;
-
- if(pipe(fd1)!=0)
- {
- printf("pipe1 failed\n");
- exit(1);
- }
- if(pipe(fd2)!=0)
- {
- printf("pipe2 failed\n");
- exit(1);
- }
- pid=fork();
- switch(pid)
- {
- case 0:
- //read from pipe1
- close(fd1[1]);
- //write to pipe2
- close(fd2[0]);
- child_rw_pipe(fd1[0],fd2[1]);
- exit(0);
- case -1:
- printf("fork error!\n");
- exit(1);
- default:
- //read from pipe2
- close(fd2[1]);
- //write to pipe1
- close(fd1[0]);
- parent_rw_pipe(fd2[0],fd1[1]);
- wait(&stat_val);
- exit(0);
- }
-
- return 0;
- }
作者: edsionte 发布时间: 2010-07-24
顶以下。。
作者: edsionte 发布时间: 2010-07-25
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28