使用管道实现AB两个进程的相互通信(提示:每个程序都可以使用多进程、多线程)
#include <myhead.h>
int main(int argc,const char *argv[])
{
if(mkfifo("./AtoB",0664))//a输出b的文件
{
perror("AtoB error");
return -1;
}
if(mkfifo("./BtoA",0664))//b输出到a的文件
{
perror("BtoA error");
return -1;
}
return 0;
}
A.c
#include <myhead.h>
void *areadb(void *arg)
{
int f1;
if((f1=open("./BtoA",O_RDONLY))==-1)//打开文件
{
perror("open error1");
return NULL;
}
while(1)
{
char a[128]="";
read(f1,a,sizeof(a));//从b读消息
if(a[0]=='\n')//只有换行则结束
{
break;
}
printf("收到消息:%s",a);//输出收到的消息
}
close(f1);//关闭文件
return NULL;
}
void *awriteb(void *arg)
{
int f2;
if((f2=open("./AtoB",O_WRONLY))==-1)//打开文件
{
perror("open error2");
return NULL;
}
while(1)
{
char buf[128]="";
fgets(buf,sizeof(buf),stdin);//输入数据
write(f2,buf,strlen(buf));//往b输出数据
if(buf[0]=='\n')//不输入则结束
{
break;
}
}
close(f2);//关闭文件
return NULL;
}
int main(int argc,const char *argv[])
{
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,areadb,NULL))//第一个线程接受b的数据
{
perror("tid1 error");
return -1;
}
if(pthread_create(&tid2,NULL,awriteb,NULL))//第二个线程往b写数据
{
perror("tid2 error");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
B.c
#include <myhead.h>
void *areadb(void *arg)
{
int f1;
if((f1=open("./AtoB",O_RDONLY))==-1)//打开文件
{
perror("open error");
return NULL;
}
while(1)
{
char a[128]="";
read(f1,a,sizeof(a));//读取a输出的数据
if(a[0]=='\n')//关闭
{
break;
}
printf("收到消息:%s",a);//输出
}
close(f1);//关闭文件
return NULL;
}
void *awriteb(void *arg)
{
int f2;
if((f2=open("./BtoA",O_WRONLY))==-1)//打开文件
{
perror("open error");
return NULL;
}
while(1)
{
char buf[128]="";
fgets(buf,sizeof(buf),stdin);//输入数据
write(f2,buf,strlen(buf));//往管道写数据
if(buf[0]=='\n')
{
break;
}
}
close(f2);//关闭文集
return NULL;
}
int main(int argc,const char *argv[])
{
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,areadb,NULL))//线程读取a
{
perror("tid1 error");
return -1;
}
if(pthread_create(&tid2,NULL,awriteb,NULL))//线程往a
{
perror("tid2 error");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}