使用有名管道实现两个进程之间的通信
进程A
#include <myhead.h>
int main(int argc, const char *argv[])
{//创建两个文件描述符用于打开两个管道int fd1=-1;int fd2=-1;//创建一个子进程int pid=-1;if((fd1=open("./mkfifo1",O_RDWR))==-1){perror("open error");return -1;}if((fd2=open("./mkfifo2",O_RDWR))==-1){perror("open error");return -1;}pid=fork();if(pid==0){//子char rbuf[128]="";//创建一个用于接收进程B发来的消息的容器while(1){bzero(rbuf,sizeof(rbuf));//容器清零read(fd1,rbuf,sizeof(rbuf));//读取数据printf("收到消息:%s\n",rbuf);if(strcmp(rbuf,"quit")==0)//退出条件{break;}}close(fd1);//关闭管道close(fd2);exit(EXIT_SUCCESS);//关闭子进程}else if(pid>0){//父char wbuf[128]="";//创建一个用于向进程B写入数据的容器while(1){bzero(wbuf,sizeof(wbuf));//容器清零read(0,wbuf,sizeof(wbuf));//终端写入wbuf[strlen(wbuf)-1]=0;//将'\n'替换成'\0'write(fd2,wbuf,sizeof(wbuf));//写入数据if(strcmp(wbuf,"quit")==0){break;}}close(fd1);close(fd2);wait(NULL);//回收子进程}else{perror("fork error");return -1;}return 0;
}
进程B
#include <myhead.h>
int main(int argc, const char *argv[])
{int fd1=-1;int fd2=-1;int pid=-1;if((fd1=open("./mkfifo1",O_RDWR))==-1){perror("open error");return -1;}if((fd2=open("./mkfifo2",O_RDWR))==-1){perror("open error");return -1;}pid=fork();if(pid==0){//子char wbuf[128]="";while(1){bzero(wbuf,sizeof(wbuf));read(0,wbuf,sizeof(wbuf));wbuf[strlen(wbuf)-1]=0;write(fd1,wbuf,sizeof(wbuf));if(strcmp(wbuf,"quit")==0){break;}}close(fd1);close(fd2);exit(EXIT_SUCCESS);}else if(pid>0){//父char rbuf[128]="";while(1){bzero(rbuf,sizeof(rbuf));read(fd2,rbuf,sizeof(rbuf));printf("收到消息:%s\n",rbuf);if(strcmp(rbuf,"quit")==0){break;}}close(fd1);close(fd2);wait(NULL);}else{perror("fork error");return -1;}return 0;
}
两个有名管道
#include <myhead.h>
int main(int argc, const char *argv[])
{//创建两个有名管道if(mkfifo("./mkfifo1",0664)==-1){perror("mkfifo1 error");return -1;}if(mkfifo("./mkfifo2",0664)==-1){perror("mkfifo2 error");return -1;}getchar();//自此处阻塞system("rm mkfifo1 mkfifo2");//结束时删除两个有名管道return 0;
}
效果图