编制一段程序,实现进程的管道通信。使用系统调用pipe()建立一条管道线。两个子进程p1和p2分别向管道各写一句话:
而父进程则从管道中读出来自两个子进程的信息,显示在屏幕上。
#include<stdio.h>
#include<unistd.h>//添加fork()函数头文件
#include<signal.h>//signal头文件
#include<stdlib.h>//exit需头文件
int main(){
int fd[3],pid1,pid2;
char OutPipe[100],InPipe[100];
pipe(fd);//创建管道,fd[0]指向管道的读端,fd[1]指向管道的写端
while((pid1=fork())==-1);
if(pid1==0){
printf("p1\n");
lockf(fd[1],1,0);
sprintf(OutPipe,"child1 is sending a message!");//给OutPipe赋值
write(fd[1],OutPipe,50);
sleep(1);
lockf(fd[1],0,0);
exit(0);
}else{
while((pid2=fork())==-1);
if(pid2==0){
printf("p2\n");
lockf(fd[1],1,0);
sprintf(OutPipe,"child2 is sending a message!");
write(fd[1],OutPipe,50);
sleep(1);
lockf(fd[1],0,0);
exit(0);
}else{
printf("parent\n");
wait(0);
read(fd[0],InPipe,50);
printf("%s\n",InPipe);
wait(0);
read(fd[0],InPipe,50);
printf("%s\n",InPipe);
exit(0);
}
}
return 0;
}
运行截图: