//chatA
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
int main(){
int ret=access("fifo1",F_OK);
if(ret==-1)
{
ret = mkfifo("fifo1",0664);
if(ret==-1)
{
perror("mkfifo1");
exit(0);
}
}
ret=access("fifo2",F_OK);
if(ret==-1)
{
ret = mkfifo("fifo2",0664);
if(ret==-1)
{
perror("mkfifo2");
exit(0);
}
}
int fdw = open("fifo1",O_WRONLY);
if(fdw==-1){
perror("open");
exit(0);
}
printf("打开管道fifo1成功,等待写入...");
int fdr = open("fifo2",O_RDONLY);
if(fdr==-1){
perror("open");
exit(0);
}
printf("打开管道fifo2成功,等待读取...");
//4.循环的写读数据
char buf[128];
while(1){
//
memset(buf,0,128);
fgets(buf,128,stdin);
//写数据
ret = write(fdw,buf,strlen(buf));
if(ret==-1){
perror("write");
exit(0);
}
//读数据
memset(buf,0,128);
ret=read(fdr,buf,128);
if(ret<=0)
{
perror("read");
break;
}
printf("data from chat2:%s
",buf);
}
close(fdr);
close(fdw);
return 0;
}
//chatB.c
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
int main(){
int ret=access("fifo1",F_OK);
if(ret==-1)
{
ret = mkfifo("fifo1",0664);
if(ret==-1)
{
perror("mkfifo1");
exit(0);
}
}
ret=access("fifo2",F_OK);
if(ret==-1)
{
ret = mkfifo("fifo2",0664);
if(ret==-1)
{
perror("mkfifo2");
exit(0);
}
}
int fdr = open("fifo1",O_RDONLY);
if(fdr==-1){
perror("open");
exit(0);
}
printf("打开管道fifo1成功,等待读取...");
int fdw = open("fifo2",O_WRONLY);
if(fdw==-1){
perror("open");
exit(0);
}
printf("打开管道fifo2成功,等待写入...");
//4.循环的写读数据
char buf[128];
while(1){
memset(buf,0,128);
ret=read(fdr,buf,128);
if(ret<=0)
{
perror("read");
break;
}
printf("data from chat1:%s
",buf);
memset(buf,0,128);
fgets(buf,128,stdin);
//写数据
ret = write(fdw,buf,strlen(buf));
if(ret==-1){
perror("write");
exit(0);
}
//读数据
}
close(fdr);
close(fdw);
return 0;
}