代码示例:
(head.h)
#ifndef _HEAD_H
#define _HEAD_H
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/wait.h>
#include<fcntl.h>
#include<pthread.h>
#include<semaphore.h>
#endif
(write.c)
#include"head.h"
int fdA = 0;
int fdB = 0;
char tmpbuff[1024] = {0};
void *threadA(void *arg)
{
while (1)
{
memset(tmpbuff, 0, sizeof(tmpbuff));
gets(tmpbuff);
write(fdA, tmpbuff, strlen(tmpbuff));
if (!strcmp(tmpbuff, "quite"))
{
break;
}
}
return NULL;
}
void *threadB(void *arg)
{
while (1)
{
memset(tmpbuff, 0, sizeof(tmpbuff));
read(fdB, tmpbuff, sizeof(tmpbuff));
printf("B: %s\n", tmpbuff);
if (!strcmp(tmpbuff, "quite"))
{
break;
}
}
return NULL;
}
int main(void)
{
pthread_t tidA;
pthread_t tidB;
mkfifo("/tmp/myfifoA", 0664);
fdA = open("/tmp/myfifoA", O_WRONLY);
if (-1 == fdA)
{
perror("open");
exit(1);
}
fdB = open("/tmp/myfifoB", O_RDONLY);
if (-1 == fdB)
{
perror("open");
exit(1);
}
pthread_create(&tidA, NULL, threadA, NULL);
pthread_create(&tidB, NULL, threadB, NULL);
pthread_join(tidA, NULL);
pthread_join(tidB, NULL);
close(fdA);
close(fdB);
return 0;
}
(read.c)
#include"head.h"
int fdA = 0;
int fdB = 0;
char tmpbuff[1024] = {0};
void *threadA(void *arg)
{
while (1)
{
memset(tmpbuff, 0, sizeof(tmpbuff));
read(fdA, tmpbuff, sizeof(tmpbuff));
printf("A: %s\n", tmpbuff);
if (!strcmp(tmpbuff, "quite"))
{
break;
}
}
return NULL;
}
void *threadB(void *arg)
{
while (1)
{
memset(tmpbuff, 0, sizeof(tmpbuff));
gets(tmpbuff);
write(fdB, tmpbuff, strlen(tmpbuff));
if (!strcmp(tmpbuff, "quite"))
{
break;
}
}
return NULL;
}
int main(void)
{
pthread_t tidA;
pthread_t tidB;
mkfifo("/tmp/myfifoB", 0664);
fdA = open("/tmp/myfifoA", O_RDONLY);
if (-1 == fdA)
{
perror("open");
exit(1);
}
fdB = open("/tmp/myfifoB", O_WRONLY);
if (-1 == fdB)
{
perror("open");
exit(1);
}
pthread_create(&tidA, NULL, threadA, NULL);
pthread_create(&tidB, NULL, threadB, NULL);
pthread_join(tidA, NULL);
pthread_join(tidB, NULL);
close(fdA);
close(fdB);
return 0;
}