+ -
当前位置:首页 → 问答吧 → 实现进程间全双工通道的问题

实现进程间全双工通道的问题

时间:2010-07-24

来源:互联网

下面的代码是实现进程间的全双工通道。今天我在调试下面的代码的时候,遇到了这样一个问题,在child_rw_pipe函数中(parent_rw_piep函数也是如此)如果我先read,再write。程序运行时就会没反应。但是先write再read就可以正确运行处结果。麻烦大家分析一下为什么?
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <unistd.h>
  5. #include <string.h>

  6. void child_rw_pipe(int readfd,int writefd)
  7. {
  8.         char message1[100],*message2="The message was wrote to pipe2! Now you read it from pipe2.";

  9.         printf("enter child\n");
  10.         //child process write message to pipe2
  11.         write(writefd,message2,strlen(message2)+1);
  12.         //child process read message from pipe1
  13.         read(readfd,message1,100);
  14.         printf("read from pipe1:%s\n",message1);
  15. }

  16. void parent_rw_pipe(int readfd,int writefd)
  17. {
  18.         char message2[100],*message1="The message was wrote to pipe1! Now you read it from pipe1.";

  19.         printf("enter parent\n");
  20.         //parent process write message to pipe1
  21.         write(writefd,message1,strlen(message1)+1);
  22.         //parent process read message from pipe2
  23.         read(readfd,message2,100);
  24.         printf("read from pipe2:%s\n",message2);
  25. }

  26. int main()
  27. {
  28.         int fd1[2],fd2[2];
  29.         pid_t pid;
  30.         int stat_val;

  31.         if(pipe(fd1)!=0)
  32.         {
  33.                 printf("pipe1 failed\n");
  34.                 exit(1);
  35.         }
  36.         if(pipe(fd2)!=0)
  37.         {
  38.                 printf("pipe2 failed\n");
  39.                 exit(1);
  40.         }
  41.         pid=fork();
  42.         switch(pid)
  43.         {
  44.                 case 0:
  45.                         //read from pipe1
  46.                         close(fd1[1]);
  47.                         //write to pipe2
  48.                         close(fd2[0]);
  49.                         child_rw_pipe(fd1[0],fd2[1]);
  50.                         exit(0);
  51.                 case -1:
  52.                         printf("fork error!\n");
  53.                         exit(1);
  54.                 default:
  55.                         //read from pipe2
  56.                         close(fd2[1]);
  57.                         //write to pipe1
  58.                         close(fd1[0]);
  59.                         parent_rw_pipe(fd2[0],fd1[1]);
  60.                         wait(&stat_val);
  61.                         exit(0);
  62.         }

  63.         return 0;
  64. }
复制代码

作者: edsionte   发布时间: 2010-07-24

顶以下。。

作者: edsionte   发布时间: 2010-07-25

相关阅读 更多