要求实现AB进程对话
a.A进程先发送一句话给B进程,B进程接收后打印
b.B进程再回复一句话给A进程,A进程接收后打印
c.重复1.2步骤,当收到quit后,要结束AB进程
A进程
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<head.h>
int main(int argc, const char *argv[])
{
if(mkfifo("./fifo",0664)<0)
{
if(errno!=17)
{
ERR_MSG("mkfifo");
return -1;
}
}
printf("mkfifo success\n");
int fd=open("./fifo",O_RDWR);
if(fd<0)
{
ERR_MSG("open");
return -1;
}
printf("open success fd=%d\n",fd);
char buf[128]="";
char str[128]="";
ssize_t res=0;
ssize_t res1=0;
while(1)
{
printf("请输入");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]='\0';
if((res=write(fd,buf,sizeof(buf)))<0)
{
ERR_MSG("write");
return -1;
}
if(strcmp(buf,"quit")==0)
break;
printf("写入成功\n");
sleep(3);
res1=read(fd,str,sizeof(str));
if(strcmp(str,"quit")==0)
break;
if(res1<0)
{
ERR_MSG("read");
return -1;
}
if(0==res1)
{
printf("写端关闭\n");
break;
}
printf("%s",str);
}
close(fd);
return 0;
}
B进程
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<head.h>
int main(int argc, const char *argv[])
{
if(mkfifo("./fifo",0664)<0)
{
if(errno!=17)
{
ERR_MSG("mkfifo");
return -1;
}
}
printf("mkfifo success\n");
int fd=open("./fifo",O_RDWR);
if(fd<0)
{
ERR_MSG("open");
return -1;
}
printf("open success fd=%d\n",fd);
char buf[128]="";
char str[128]="";
ssize_t res=0;
ssize_t res1=0;
while(1)
{
sleep(2);
bzero(buf,sizeof(buf));
res=read(fd,buf,sizeof(buf));
if(strcmp(buf,"quit")==0)
break;
if(res<0)
{
ERR_MSG("read");
return -1;
}
if(0==res)
{
printf("写端关闭\n");
break;
}
printf("%s\n",buf);
printf("请输入");
fgets(str,sizeof(str),stdin);
str[strlen(str)-1]='\0';
if((res1=write(fd,str,sizeof(str)))<0)
{
ERR_MSG("write");
return -1;
}
printf("%s",str);
if(strcmp(str,"quit")==0)
break;
printf("%d\n",strcmp(str,"quit"));
printf("写入成功\n");
}
close(fd);
return 0;
}