create.c
#include <myhead.h>
int main(int argc, const char *argv[])
{
//创建有名管道
if(mkfifo("./myfifo",0664))
{
perror("");
return -1;
}
printf("create success\n");
//创建有名管道
if(mkfifo("./myfifo1",0664))
{
perror("");
return -1;
}
printf("create success\n");
//使用getchar阻塞一下
getchar();
system("rm myfifo myfifo1");
return 0;
}
send.c
#include <myhead.h>
void *task(void *arg)
{
//以只读的形式代开管道文件
int rfd=-1;
if((rfd=open("./myfifo1",O_RDONLY))==-1)
{
perror("");
//return;
}
printf("读端打开成功\n");
//
char rbuf[128]="";
while(1)
{
bzero(rbuf,sizeof(rbuf));
//从管道中读取数据
read(rfd,rbuf,sizeof(rbuf));
printf("收到消息为:%s\n",rbuf);
if(strcmp(rbuf,"quit")==0)
break;
}
pthread_exit(NULL);
close(rfd);
}
int main(int argc, const char *argv[])
{
pthread_t tid;
if(pthread_create(&tid, NULL, task, NULL) != 0)
{
printf("tid create error\n");
return -1;
}
//以只写的形式打开管道文件
int wfd=-1;
if((wfd=open("./myfifo",O_WRONLY))==-1)
{
perror("");
return -1;
}
printf("写端打开成功\n");
//
char wbuf[128]="";
while(1)
{
bzero(wbuf,sizeof(wbuf));
//
printf("请输入>>");
fflush(stdout);
read(0,wbuf,sizeof(wbuf));
wbuf[strlen(wbuf)-1]=0;
//
write(wfd,wbuf,sizeof(wbuf));
if(strcmp(wbuf,"quit")==0)
break;
}
pthread_join(tid,NULL);
close(wfd);
return 0;
}
receive.c
#include <myhead.h>
void *task(void *arg)
{
//以只写的形式打开管道文件
int wfd=-1;
if((wfd=open("./myfifo1",O_WRONLY))==-1)
{
perror("");
}
//
char wbuf[128]="";
while(1)
{
bzero(wbuf,sizeof(wbuf));
printf("请输入>>");
fflush(stdout);
read(0,wbuf,sizeof(wbuf));
wbuf[strlen(wbuf)-1]=0;
write(wfd,wbuf,sizeof(wbuf));
if(strcmp(wbuf,"quit")==0)
break;
}
pthread_exit(NULL);
close(wfd);
}
int main(int argc, const char *argv[])
{
pthread_t tid;
//创建一个分支线程
if(pthread_create(&tid, NULL, task, NULL) != 0)
{
printf("tid create error\n");
return -1;
}
//以只读的形式代开管道文件
int rfd=-1;
if((rfd=open("./myfifo",O_RDONLY))==-1)
{
perror("");
return -1;
}
printf("读端打开成功\n");
//
char rbuf[128]="";
while(1)
{
bzero(rbuf,sizeof(rbuf));
//从管道中读取数据
read(rfd,rbuf,sizeof(rbuf));
printf("收到消息为:%s\n",rbuf);
if(strcmp(rbuf,"quit")==0)
break;
}
pthread_join(tid,NULL);
close(rfd);
return 0;
}