A程序代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, const char *argv[])
{
if(mkfifo("./fifo1",0664)<0)
{
if(errno !=17){
perror("mkfifo");
return -1;
}
}
if(mkfifo("./fifo2",0664)<0)
{
if(errno !=17){
perror("mkfifo");
return -1;
}
}
printf("mkfifo success\n");
int fd1 = open("./fifo1",O_WRONLY);
if(fd1<0){
perror("open");
return -1;
}
int fd2=open("./fifo2",O_RDONLY);
if(fd2<0){
perror("open_fifo2");
return-1;
}
printf("open RDONLY NONBLOCK success\n");
char buf[128];
ssize_t res;
while(1){
printf("输入数据>>\n");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]='\0';
if(write(fd1,buf,sizeof(buf))<0){
perror("write");
return -1;
}
printf("写入成功\n");
if(strcmp(buf,"quit")==0){
break;
}
//读数据i
bzero(buf,sizeof(buf));
res=read(fd2,buf,sizeof(buf));
if(res<0){
perror("read");
return -1;
}
else if(res==0){
printf("写端关闭,且管道没有数据");
break;
}
printf("fd2:%ld %s\n",res,buf);
}
close(fd2);
close(fd1);
return 0;
}
B程序代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, const char *argv[])
{
if(mkfifo("./fifo1",0664)<0)
{
if(errno !=17){
perror("mkfifo");
return -1;
}
}
if(mkfifo("./fifo2",0664)<0)
{
if(errno !=17){
perror("mkfifo");
return -1;
}
}
printf("mkfifo success\n");
pid_t pid;
int fd1 = open("./fifo1",O_RDONLY);
if(fd1<0){
perror("open");
return -1;
}
int fd2 = open("./fifo2",O_WRONLY);
if(fd2<0){
perror("open");
return -1;
}
printf("open RDONLY NONBLOCK success\n");
char buf[128];
ssize_t res;
while(1){
bzero(buf,sizeof(buf));
res=read(fd1,buf,sizeof(buf));
if(res<0){
perror("read");
return -1;
}
else if(0==res){
printf("写端关闭,且管道里没有数据\n");
break;
}
printf("%ld :%s \n",res,buf);
//写数据
bzero(buf,sizeof(buf));
printf("输入数据>>\n");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]='\0';
if(write(fd2,buf,sizeof(buf))<0){
perror("write");
return -1;
}
printf("fd2_写入成功\n");
if(strcmp(buf,"quit")==0){
break;
}
}
close(fd2);
close(fd1);
return 0;
}
运行结果: