完成父子进程的通信,
父进程发送一句话后,子进程接收打印
然后子进程发送一句话,父进程接收后打印
- #include
- int main(int argc, char const *argv[])
- {
- //创建第一个管道
- if(mkfifo("./fifo_1",0664)<0){
- if(errno!=17){
- perror("mkfifo");
- return -1;
- }
- }
- //创建第二个管道
- if(mkfifo("./fifo_2",0664)<0){
- if(errno!=17){
- perror("mkfifo");
- return -1;
- }
- }
- pid_t cpid=fork();
- if(cpid>0){
- //打开
- char buf[128]="";
- while(1){
- //打开第一个管道(写)
- int fp1=open("./fifo_1",O_WRONLY);
- if(fp1<0){
- perror("open");
- return -1;
- }
- bzero(buf,sizeof(buf));
- printf("父输入数据为>>>");
- fgets(buf,sizeof(buf),stdin);
- buf[strlen(buf)-1]='\0';
- if(strcmp(buf,"quit")==0){
- puts("退出输入");
- break;
- }
- write(fp1,buf,sizeof(buf));
- puts("发送成功");
- //关闭第一个管道
- close(fp1);
- //打开第二个管道(读)
- int fp2=open("./fifo_2",O_RDONLY);
- if(fp2<0){
- perror("open");
- return -1;
- }
- bzero(buf,sizeof(buf));
- off_t res=read(fp2,buf,sizeof(buf));
- printf("父读取数据为>>>>%s\n",buf);
- if(0==res){
- puts("数据读取完成");
- break;
- }
- //关闭第二个管道
- close(fp2);
- }
- }
- if(0==cpid){
- //打开
- char buf[128]="";
- while(1){
- //打开第一个管道(读)
- int fp1=open("./fifo_1",O_RDONLY);
- if(fp1<0){
- perror("open");
- return -1;
- }
- bzero(buf,sizeof(buf));
- off_t res=read(fp1,buf,sizeof(buf));
- printf("子读取数据为>>>>%s\n",buf);
- if(0==res){
- puts("数据读取完成");
- break;
- }
- //关闭第一个管道
- close(fp1);
- //打开第二个管道(写)
- int fp2=open("./fifo_2",O_WRONLY);
- if(fp2<0){
- perror("open");
- return -1;
- }
- bzero(buf,sizeof(buf));
- printf("子输入数据为>>>");
- fgets(buf,sizeof(buf),stdin);
- buf[strlen(buf)-1]='\0';
- if(strcmp(buf,"quit")==0){
- puts("退出输入");
- break;
- }
- write(fp2,buf,sizeof(buf));
- puts("发送成功");
- //关闭第二个管道
- close(fp2);
- }
- }
- return 0;
- }