#include <stdio.h> #include <sys/types.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #include <error.h> #include <wait.h> #include <unistd.h> int main( ){ int pid1,pid2,pid3; int fd[2]; char outpipe[60],inpipe[60]; pipe(fd);//创建一个管道 whil
时间: 2023-09-13 12:04:40 浏览: 44
e((pid1=fork())==-1); //创建第一个子进程 if(pid1==0){ //子进程1的代码 close(fd[0]); //关闭读端 sprintf(outpipe,"Child process 1 is sending a message!"); write(fd[1],outpipe,60);//写入管道 exit(0);//子进程1退出 } else{ //父进程继续创建第二个子进程 while((pid2=fork())==-1); if(pid2==0){ //子进程2的代码 close(fd[1]);//关闭写端 read(fd[0],inpipe,60);//读取管道内容 printf("Child process 2 received a message: %s\n",inpipe); exit(0);//子进程2退出 } else{ //父进程继续创建第三个子进程 while((pid3=fork())==-1); if(pid3==0){ //子进程3的代码 close(fd[0]);//关闭读端 close(fd[1]);//关闭写端 printf("Child process 3 is running!\n"); exit(0);//子进程3退出 } else{ //父进程等待三个子进程结束 waitpid(pid1,NULL,0); waitpid(pid2,NULL,0); waitpid(pid3,NULL,0); printf("All child processes have finished!\n"); exit(0);//父进程退出 } } } return 0; }
这是一段使用管道实现进程间通信的程序,其中通过创建三个子进程,实现了进程间的消息传递和同步执行。第一个子进程向管道中写入一个消息,第二个子进程从管道中读取消息并输出,第三个子进程只是为了演示多进程的使用,没有实际作用。
以上是我的回答,是否能满足你的问题?