A进程
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
int fd,fd2;
char buf[20]="";
char buf2[20]="";
void* send_A(void *arg){
while(1){
bzero(buf,sizeof(buf));
printf("请输入\n");
scanf("%s",buf);
printf("A进程发送了%s\n",buf);
write(fd,buf,strlen(buf));
if(0==strncmp(buf,"quit",4)){
break;
}
}
pthread_exit(NULL);
}
void* receive_A(void *arg){
while(1){
bzero(buf2,sizeof(buf2));
read(fd2,buf2,sizeof(buf2));
if(0==strncmp(buf2,"quit",4)){
break;
}
printf("A进程接收了%s\n",buf2);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
umask(0);
if(mkfifo("./fifo1",0777)<0){
if(17!=errno){
perror("mkfifo");
return -1;
}
}
printf("fifo1 create success\n");
if(mkfifo("./fifo2",0777)<0){
if(17!=errno){
perror("mkfifo");
return -1;
}
}
printf("fifo2 create success\n");
fd=open("./fifo1",O_WRONLY);
fd2=open("./fifo2",O_RDONLY);
if(fd<0){
perror("open");
return -2;
}
if(fd2<0){
perror("open");
return -2;
}
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,send_A,NULL);
pthread_create(&tid1,NULL,receive_A,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
B进程
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
int fd,fd2;
char buf[20]="";
char buf2[20]="";
void* send_B(void *arg){
while(1){
bzero(buf,sizeof(buf));
printf("请输入\n");
scanf("%s",buf);
printf("B进程发送了%s\n",buf);
write(fd2,buf,strlen(buf));
if(0==strncmp(buf,"quit",4)){
break;
}
}
pthread_exit(NULL);
}
void* receive_B(void *arg){
while(1){
bzero(buf2,sizeof(buf2));
read(fd,buf2,sizeof(buf2));
if(0==strncmp(buf2,"quit",4)){
break;
}
printf("B进程接收了%s\n",buf2);
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
umask(0);
if(mkfifo("./fifo1",0777)<0){
if(17!=errno){
perror("mkfifo");
return -1;
}
}
printf("fifo1 create success\n");
if(mkfifo("./fifo2",0777)<0){
if(17!=errno){
perror("mkfifo");
return -1;
}
}
printf("fifo2 create success\n");
fd=open("./fifo1",O_RDONLY);
fd2=open("./fifo2",O_WRONLY);
if(fd<0){
perror("open");
return -2;
}
if(fd2<0){
perror("open");
return -2;
}
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,send_B,NULL);
pthread_create(&tid1,NULL,receive_B,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}