管道A:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
if(mkfifo("./myfifo",0777)<0)
{
if(errno != 17)
{
perror("mkfifo1");
return -1;
}
}
printf("管道1创建成功!\n");
if(mkfifo("./myfifo2",0777) <0)
{
if(errno !=17 )
{
perror("mkfifo");
return -1;
}
}
printf("管道2创建成功!\n");
int op = open("./myfifo",O_WRONLY);//打开管道1的写
int op1 = open("./myfifo1",O_RDONLY);//打开管道2的读
if(op<0 || op1<0)
{
perror("open");
return -1;
}
printf("管道1写打开成功/2读打开成功!\n");
char arr[128] = "";
ssize_t res = 0;
while(1)
{
//读端
bzero(arr,sizeof(arr));
res = read(op1,arr,sizeof(arr));
//fgets(arr,sizeof(arr),stdin);
if(res <0)
{
perror("read");
return -1;
}else if(res == 0)
{
printf("写端关闭!\n");
break;
}
if(strcmp(arr,"quit") == 0)
{
break;
}
printf("%s \n",arr);
//写端
printf("罗密欧说:");
fgets(arr,sizeof(arr),stdin);
arr[strlen(arr)-1] = '\0';
if(write(op,arr,sizeof(arr))<0)
{
perror("write");
return -1;
}else
printf(" ");
if(strcmp(arr,"quit") == 0)
{
printf("罗密欧退出!\n");
break;
}
}
close(op);
close(op1);
return 0;
}
管道B:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
if(mkfifo("./myfifo",0777) <0)
{
if(errno !=17 )
{
perror("mkfifo");
return -1;
}
}
printf("管道1创建成功!\n");
if(mkfifo("./myfifo1",0777) <0)
{
if(errno !=17 )
{
perror("mkfifo");
return -1;
}
}
printf("管道2创建成功!\n");
int op = open("./myfifo",O_RDONLY);//打开管道1的读
int op1 = open("./myfifo1",O_WRONLY);//打开管道2的写
printf("管道1读打开成功/2写打开成功\n");
char arr[128] = "";
ssize_t res = 0;
//写端
while(1)
{
printf("朱丽叶说:");
fgets(arr,sizeof(arr),stdin);
arr[strlen(arr)-1] = '\0';
if(write(op1,arr,strlen(arr))<0)
{
perror("write");
return -1;
}
printf(" ");
if(strcmp(arr,"quit") == 0 )
{
printf("朱丽叶退出\n");
break;
}
//读端
bzero(arr,sizeof(arr));
res = read(op,arr,sizeof(arr));
if(res <0)
{
perror("read");
return -1;
}else if(res == 0)
{
printf("写端关闭!\n");
break;
}
if(strcmp(arr,"quit") == 0)
{
break;
}
printf("%s \n",arr);
// close(op);
// printf("op以关闭\n");
}
if(close(op)<0 || close(op1)<0)
{
perror("read");
perror("write");
return -1;
}
return 0;
}