#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <pthread.h>
char buf[128] = "";
ssize_t res = 0;
pthread_t tid_r,tid_w;
//临界资源
void* callBack1(void* arg)
{
//以写的方式打开fifo1
int fd_w = open("./fifo1", O_WRONLY);
if(fd_w < 0)
{
perror("open");
return NULL;
}
while(1)
{
bzero(buf,sizeof(buf));
printf("请输入>>>");
scanf("%s", buf);
while(getchar() != 10); //循环吸收垃圾字符
if(write(fd_w, buf, sizeof(buf)) < 0)
{
perror("write");
return NULL;
}
if(strcasecmp(buf, "quit") == 0)
break;
}
close(fd_w);
pthread_cancel(tid_w);
pthread_exit(NULL);
}
void* callBack2(void* arg)
{
//以读的方式打开fifo2
int fd_r = open("./fifo2", O_RDONLY);
if(fd_r < 0)
{
perror("open");
return NULL;
}
while(1)
{
//向fifo1写入
bzero(buf, sizeof(buf));
//从fifo2读取
res = read(fd_r, buf, sizeof(buf));
if(res < 0)
{
perror("read");
return NULL;
}
else if(0 == res)
{
printf("fifo2的写端关闭\n");
break;
}
printf(":%s\n", buf);
if(strcasecmp(buf, "quit") == 0)
break;
}
close(fd_r);
pthread_cancel(tid_r);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//创建有名管道文件
if(mkfifo("./fifo1", 0664) < 0) //向fifo1写入数据
{
if(17 != errno)
{
perror("mkfifo");
return -1;
}
}
if(mkfifo("./fifo2", 0664) < 0) //从fifo2读取数据
{
if(17 != errno)
{
perror("mkfifo");
return -1;
}
}
//创建线程1
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,callBack1,NULL)!=0)
{
perror("pthread_create");
return -1;
}
//创建线程2
if(pthread_create(&tid2,NULL,callBack2,NULL)!=0)
{
perror("pthread_create");
return -1;
}
pthread_join(tid_w,NULL);
pthread_join(tid_r,NULL);
return 0;
}