尽力了,搞不出来,输入会阻塞占用终端,无法输出接收到的字符串.
creat.c:
#include<myhead.h>
int main(int argc, const char *argv[])
{
//创建管道文件
if(mkfifo("./myfifoAtoB",0664)==-1){
perror("mkfifo error");
return -1;
}
//创建管道文件
if(mkfifo("./myfifoBtoA",0664)==-1){
perror("mkfifo error");
return -1;
}
getchar();//阻塞一下,按下回车才继续运行
system("rm myfifoAtoB");
system("rm myfifoBtoA");
return 0;
}
usrposA.c:
#include<myhead.h>
typedef struct
{
int wrfd;
pthread_t mtid;
}argu,*arguPtr;
void *task(void *arg){
arguPtr arp = (arguPtr)arg;
//打开接收的管道文件
int refd;
if((refd=open("./myfifoBtoA",O_RDONLY))==-1){
perror("open error");
return NULL;
}
while(1){
char buf[128] = "";
//从管道中读取数据
read(refd,buf,sizeof(buf));
if(strcmp(buf,"quit")==0){
write(arp->wrfd,"quit",4);
//提示主线程应该结束了
pthread_cancel(arp->mtid);
close(arp->wrfd);
break;
}
printf("读取的信息为:%s\n",buf);
}
//关闭文件
close(refd);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//定义一个子线程号
pthread_t tid;
//打开传送数据管道文件
int wrfd;
if((wrfd=open("./myfifoAtoB",O_WRONLY))==-1){
perror("open error");
return -1;
}
argu arg1 = {wrfd,pthread_self()};
//创建一个子线程
if(pthread_create(&tid,NULL,task,&arg1)==-1){
printf("pthread_creat error\n");
return -1;
}
//这是主线程,专门用来发送
while(1){
char buf[128] = "";
fgets(buf,sizeof(buf),stdin); //输入数据
buf[strlen(buf)-1] = 0;
//将数据写入管道中
write(wrfd,buf,strlen(buf));
if(strcmp(buf,"quit")==0){
printf("再见,亲爱的B\n");
break;
}
}
//关闭文件
close(wrfd);
pthread_join(tid,NULL);
return 0;
}
usrposB.c:
#include<myhead.h>
typedef struct
{
int wrfd;
pthread_t mtid;
}argu,*arguPtr;
void *task(void *arg){
arguPtr arp = (arguPtr)arg;
//打开接收的管道文件
int refd;
if((refd=open("./myfifoAtoB",O_RDONLY))==-1){
perror("open error");
return NULL;
}
while(1){
char buf[128] = "";
//从管道中读取数据
read(refd,buf,sizeof(buf));
if(strcmp(buf,"quit")==0){
write(arp->wrfd,"quit",4);
//提示主线程应该结束了
pthread_cancel(arp->mtid);
close(arp->wrfd);
break;
}
printf("读取的信息为:%s\n",buf);
}
//关闭文件
close(refd);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//定义一个子线程号
pthread_t tid;
//打开传送数据管道文件
int wrfd;
if((wrfd=open("./myfifoBtoA",O_WRONLY))==-1){
perror("open error");
return -1;
}
argu arg1 = {wrfd,pthread_self()};
//创建一个子线程
if(pthread_create(&tid,NULL,task,&arg1)==-1){
printf("pthread_creat error\n");
return -1;
}
//这是主线程,专门用来发送
while(1){
char buf[128] = "";
fgets(buf,sizeof(buf),stdin); //输入数据
buf[strlen(buf)-1] = 0;
//将数据写入管道中
write(wrfd,buf,strlen(buf));
if(strcmp(buf,"quit")==0){
printf("再见,亲爱的A\n");
break;
}
}
//关闭文件
close(wrfd);
pthread_join(tid,NULL);
return 0;
}
思维导图