BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #44928同步于 2010/10/18
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

问一道作业题,关于进程之间管道通信

laofeng
2010/10/18镜像同步2 回复
题目如下: 编制一段程序,实现进程的管道通信。 使用系统调用pipe() 建立一条管道线;两个子进程P1和P2分别向管道各写一句话: Child 1 is sending a message! Child 2 is sending a message! 而父进程则从管道中读出来自于两个子进程的信息,显示在屏幕上。 要求父进程先接收子进程P1发来的消息,然后再接收子进程P2发来的消息。 代码如下: #include<sys/types.h> #include<stdio.h> #include<unistd.h> #include <fcntl.h> #include <errno.h> int main(int argc,char* argv[]) { pid_t pid1,pid2; int fd[2]; char parbuf[50],childbuf[50]; pid1 = fork(); pipe(fd); if(pid1<0){ fprintf(stderr,"childprocess1 failed"); exit(-1); } else if(pid1 == 0){ lockf(fd[1],1,0); sprintf(childbuf,"Child 1 is sending a message!\n"); write(fd[1],childbuf,50); sleep(5); lockf(fd[1],0,0); exit(0); } else{ pid2 = fork(); if(pid2<0){ fprintf(stderr,"childprocess1 failed"); exit(-1); } else if(pid2 == 0){ lockf(fd[1],1,0); sprintf(childbuf,"Child 2 is sending a message!\n"); write(fd[1],childbuf,50); sleep(5); lockf(fd[1],0,0); exit(0); } else{ wait(0); read(fd[0],parbuf,50); printf("%s",parbuf); wait(0); read(fd[0],parbuf,50); printf("%s",parbuf); exit(0); } } return 0; } 为什么在gcc上运行后只输出了Child 2 is sending a message!,完了之后程序一直在运行,没有退出?
订阅后,新回复会通过你的通知中心匿名送达。
2 条回复
potatossss机器人#1 · 2010/10/18
无责任猜测,你何不先建立pipe,然后再fork子进程1呢?你这么写,你的子进程1也会执行pipe这个系统调用的吧
zwp机器人#2 · 2010/10/18
【 在 potatossss 的大作中提到: 】 : 无责任猜测,你何不先建立pipe,然后再fork子进程1呢?你这么写,你的子进程1也会执行pipe这个系统调用的吧 恩,这样就是两组pipe,没关联了。