创建AB进程,要求如下:
- A进程先发送一句话给B进程,B进程接收到后打印到终端上;
- 在a要求之后,B进程发送一句话给A进程,A进程接收后打印。
- 重复a, b步骤,直到发送或者接收到quit后,结束AB进程。
A端
#include<stdio.h>
#include<sys/types.h>
#include<errno.h>
#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
int main(int argc, const char *argv[])
{
umask(0);
if(mkfifo("./FIFO",0777));
{
if(errno!=17)
{
perror("mkfifo");
return -1;
}
}
printf("mkfifo success\n");
char arr[128]="";
ssize_t res=0;
while(1)
{
int fd=open("./FIFO",O_WRONLY);
if(fd<0)
{
perror("open");
return -1;
}
printf("A >>>");
fgets(arr,sizeof(arr),stdin);
arr[strlen(arr)-1]=0;
res=write(fd,arr,sizeof(arr));
if(res==0||strcasecmp(arr,"quit")==0)
{
printf("对端退出\n");
close(fd);
break;
}
if(res<0)
{
perror("write");
return -1;
}
close(fd);
fd=open("./FIFO",O_RDONLY);
if(fd<0)
{
perror("open");
return -1;
}
bzero(arr,sizeof(arr));
res=read(fd,arr,sizeof(arr));
if(res<0)
{
perror("read");
return -1;
}
if(res==0||strcasecmp(arr,"quit")==0)
{
printf("对端退出\n");
close(fd);
break;
}
printf("B: %s\n",arr);
close(fd);
}
return 0;
}
B端
#include<stdio.h>
#include<sys/types.h>
#include<errno.h>
#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
int main(int argc, const char *argv[])
{
umask(0);
if(mkfifo("./FIFO",0777));
{
if(errno!=17)
{
perror("mkfifo");
return -1;
}
}
printf("mkfifo success\n");
char arr[128]="";
ssize_t res=0;
while(1)
{
int fd=open("./FIFO",O_RDONLY);
if(fd<0)
{
perror("open");
return -1;
}
bzero(arr,sizeof(arr));
res=read(fd,arr,sizeof(arr));
if(res<0)
{
perror("read");
return -1;
}
if(res==0||strcasecmp(arr,"quit")==0)
{
printf("对端退出\n");
close(fd);
break;
}
printf("A: %s\n",arr);
close(fd);
fd=open("./FIFO",O_WRONLY);
if(fd<0)
{
perror("open");
return -1;
}
printf("B >>>");
fgets(arr,sizeof(arr),stdin);
arr[strlen(arr)-1]=0;
res=write(fd,arr,sizeof(arr));
if(res==0||strcasecmp(arr,"quit")==0)
{
printf("对端退出\n");
close(fd);
break;
}
if(res<0)
{
perror("write");
return -1;
}
close(fd);
}
return 0;
}