a.c
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/wait.h>
#include<string.h>
#include<errno.h>
#include<fcntl.h>
#include<pthread.h>
#include<unistd.h>
int fpa,fpb;
char bufw[20]="";
char bufr[20]="";
void* call_back(void* val)
{
while (1)
{
read(fpb,bufr,sizeof(bufr));
if(!strcasecmp(bufr,"quit")){
printf("A进程退出\n");
break;
}else{
printf("A进程输出:%s\n",bufr);
}
bzero(bufr,sizeof(bufr));
}
pthread_exit(NULL);
}
void* call_back_a(void* value)
{
while (1)
{
printf("A进程输入:");
fgets(bufw,sizeof(bufw),stdin);
bufw[strlen(bufw)-1]=0;
write(fpa,bufw,sizeof(bufw));
if(!strcasecmp(bufw,"quit")){
printf("A进程退出\n");
break;
}
bzero(bufw,sizeof(bufw));
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
umask(0);
if(mkfifo("myfifo",0777)<0)
{
if(EEXIST!=errno){
perror("myfifo");
return -1;
}
}
if(mkfifo("my_fifo",0777)<0)
{
if(EEXIST!=errno){
perror("my_fifo");
return -1;
}
}
pthread_t p_a,p_b;
fpa = open("myfifo",O_WRONLY);
fpb = open("my_fifo",O_RDONLY);
pthread_create(&p_a,NULL,call_back,NULL);
pthread_create(&p_b,NULL,call_back_a,NULL);
pthread_join(p_a,NULL);
pthread_join(p_b,NULL);
close(fpa);
close(fpb);
return 0;
}
b.c
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/wait.h>
#include<string.h>
#include<errno.h>
#include<fcntl.h>
#include<pthread.h>
#include<unistd.h>
int fpa,fpb;
char bufw[20]="";
char bufr[20]="";
void* call_back(void* val)
{
while (1)
{
read(fpa,bufr,sizeof(bufr));
if(!strcasecmp(bufr,"quit")){
printf("B进程退出\n");
break;
}else{
printf("B进程输出:%s\n",bufr);
}
bzero(bufr,sizeof(bufr));
}
pthread_exit(NULL);
}
void* call_back_a(void* value)
{
while (1)
{
printf("B进程输入:");
fgets(bufw,sizeof(bufw),stdin);
bufw[strlen(bufw)-1]=0;
write(fpb,bufw,sizeof(bufw));
if(!strcasecmp(bufw,"quit")){
printf("B进程退出\n");
break;
}
bzero(bufw,sizeof(bufw));
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
umask(0);
if(mkfifo("myfifo",0777)<0)
{
if(EEXIST!=errno){
perror("myfifo");
return -1;
}
}
if(mkfifo("my_fifo",0777)<0)
{
if(EEXIST!=errno){
perror("my_fifo");
return -1;
}
}
pthread_t p_a,p_b;
fpa = open("myfifo",O_RDONLY);
fpb = open("my_fifo",O_WRONLY);
pthread_create(&p_a,NULL,call_back,NULL);
pthread_create(&p_b,NULL,call_back_a,NULL);
pthread_join(p_a,NULL);
pthread_join(p_b,NULL);
close(fpa);
close(fpb);
return 0;
}