找回密码
 注册
查看: 1028|回复: 2

使用管道实现两进程通信的问题。

[复制链接]
发表于 2006-4-23 00:16:20 | 显示全部楼层 |阅读模式
用管道实现两个进程之间的通信。

思想是进程a向b发消息,由b来处理。

/*由此程序创建子进程调用要通信的两个进程。
  main.c
*/

#include <stdio.h>
#include <unistd.h>

int main(){
int a_to_b[2];
        pipe(a_to_b);
        
        if(fork()==0){  /*第一个子进程*/
                int fid=0;
               
                close(a_to_b[0]);
                close(1);
               
                          dup(a_to_b[1]);  /*管道“写端”重定位到A进程的标准输出*/
                execvp(proc_a.out , ...); /*A的代码覆盖原进程*/
        }
        if(fork()==0){ /*第二个子进程*/
               
                int fid=0;
                close(a_to_b[1]);
               
                close(0);
                dup(a_to_b[0]); /*管道“读端”重定位到B进程的标准输入*/
                execvp(proc_b.out , ...);/*B的代码覆盖原进程*/
        }
        
        wait(); /*父进程,等待两个子进程返回。*/
        wait();
        return 0;
}

/*进程A, proc_a.c*/
#include<stdio.h>

int main(){
      char ch='a';

      int i=0;
      for(;i<5;i++){
         write(stdout,ch,sizeof(char)); /*发消息*/
         ch++;
      }
      return 0;
}

/*进程B, proc_b.c*/
#include <stdio.h>
int main(){
   char ch='o';
   int i=0;
   for(;i<5;i++){
     read(stdin,ch,sizeof(char));  /*读消息*/
     printf("%c\n");
  }
  return 0;
}

以上两个子进程,不知为何不能将消息写入管道。进程B每次都只打印'o'。
各位高手请帮忙指正问题。并对此程序提出您宝贵的意见。谢谢。
发表于 2006-4-24 11:02:28 | 显示全部楼层
先排版
回复

使用道具 举报

发表于 2006-5-8 16:56:25 | 显示全部楼层
[code:1]
#include <stdio.h>
#include <unistd.h>
int main(){
int a_to_b[2];
        pipe(a_to_b);
        
        if(fork()==0){  /*第一个子进程*/
                int fid=0;
                close(a_to_b[0]);
                close(1);
                          dup(a_to_b[1]);  /*管道“写端”重定位到A进程的标准输出*/
                execvp(proc_a.out , ...); /*A的代码覆盖原进程*/
        }
        if(fork()==0){ /*第二个子进程*/
                int fid=0;
                close(a_to_b[1]);
                close(0);
                dup(a_to_b[0]); /*管道“读端”重定位到B进程的标准输入*/
                execvp(proc_b.out , ...);/*B的代码覆盖原进程*/
        }
        wait(); /*父进程,等待两个子进程返回。*/
        wait();
        return 0;
}
/*进程A, proc_a.c*/
#include<stdio.h>
int main(){
      char ch='a';
      int i=0;
      for(;i<5;i++){
         write(stdout,ch,sizeof(char)); /*发消息*/
         ch++;
      }
      return 0;
}
/*进程B, proc_b.c*/
#include <stdio.h>
int main(){
   char ch='o';
   int i=0;
   for(;i<5;i++){
     read(stdin,ch,sizeof(char));  /*读消息*/
     printf("%c\n");
  }
  return 0;
}
[/code:1]
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

GMT+8, 2025-2-7 03:51 , Processed in 0.023149 second(s), 15 queries .

© 2001-2025 Discuz! Team. Powered by Discuz! X3.5.

快速回复 返回顶部 返回列表