打开两个终端,在第一个终端先执行fifo_read,创建有名管道,并且等待输入端输入
之后,再在第二个终端执行fifo_write,之后,fifo_write将向管道写入数据,此时,输出管道将有数据可读,因此被唤醒,从管道中读出数据,并显示出来。
/*fifo_read.c*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/time.h>
#include <unistd.h>
#define FIFO_FILE "/tmp/fifo.tmp"
#define MAXLEN 1024
int main()
{
int fifo,fd;
char buf[MAXLEN];
int len,i = 0;
fd_set set;
struct timeval tv;
unlink(FIFO_FILE);
if((fifo=mkfifo(FIFO_FILE,O_RDWR))<0)
{
perror("mkfifo error\n");
return 0;
}
if((fd=open(FIFO_FILE,O_RDWR))<0)
{
perror("open mkfifo error\n");
return 0;
}
FD_ZERO(&set);
//FD_SET(fd,&set);
tv.tv_sec = 5;
tv.tv_usec = 0;
while(1)
{
FD_SET(fd,&set);
if((i=select(fd+1,&set,NULL,NULL,&tv))>0)
{
printf("have data in pipe\n");
if(FD_ISSET(fd,&set))
{
len = read(fd,buf,MAXLEN);
//buf [len]= '/0';
printf("buf =%s\n",buf);
tv.tv_sec = 5;
tv.tv_usec = 0;
}
}
else if(i == 0)
{
tv.tv_sec = 5;
tv.tv_usec = 0;
printf("time out\n");
}
}
unlink(FIFO_FILE);
return 0;
}
//#gcc fifo_read.c -o fifo_read
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#define FIFO_FILE "/tmp/fifo.tmp"
#define MAXLEN 1024
int main()
{
int fifo,fd;
char buf[MAXLEN];
int len,i = 0;
memset(buf,0,sizeof(buf));
strcpy(buf,"10");
if((fifo=open(FIFO_FILE,O_RDWR))<0)
{
perror("open mkfifo error\n");
return 0;
}
while(i<10)
{
sprintf(buf,"%d",i+1);
len = write(fifo,buf,strlen(buf));
printf("send len =%d\n",len);
sleep(1);
i++;
}
return 0;
}
//#gcc fifo_write.c -o fifo_write