写源程序:fifo_write.c
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#define FIFO_SERVER "myfifo"
int main(int argc,char **argv)
{
int fd;
char w_buf[100];
int nwrite;
if((mkfifo(FIFO_SERVER,O_CREAT|O_EXCL|O_RDWR)<0)&&(errno!=EEXIST))// #define EEXIST 17 /* File exists */
//if((mkfifo(FIFO_SERVER,0777)<0)&&(errno!=EEXIST))// #define EEXIST 17 /* File exists */
// O_EXCL:如果使用O_CREAT时文件不存在,那么可返回错误信息,这一参数可测试文件是否存在函数返回值:成功:0 出错:-1
printf("cannot create fifoserver!\n");
if(fd==-1)
{
perror("open");
exit(1);
}
if(argc==1)
{
printf("please send something \n");
exit(-1);
}
strcpy(w_buf,argv[1]);
if((nwrite=write(fd,w_buf,100))==-1)
{
if(errno==EAGAIN) //#define EAGAIN 11 /* Try again */
printf("the fifo has not been read yet.please try later \n");
}
else
{
printf("write %s to the fifo \n",w_buf);
close(fd);
return 0;
}
}
/*
警告:隐式声明与内建函数 ‘memset’ 不兼容
需要包含头文件memory.h
*/
/*
open: Permission denied
chmod 777 myfifo
*/
读源程序:
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <memory.h>
#define FIFO_SERVER "myfifo"
int main()
{
char buf_r[100];
int fd;
int nread;
printf("Preparing for reading bytes ..\n");
memset(buf_r,0,sizeof(buf_r));
fd=open(FIFO_SERVER,O_RDWR|O_NONBLOCK);
if(fd==-1)
{
perror("open");
exit(1);
}
while(1)
{
memset(buf_r,0,sizeof(buf_r));
if((nread=read(fd,buf_r,100))==-1)
{
if(errno==EAGAIN)
printf("no data yet \n");
}
printf("read %s from FIFO_SERVER \n",buf_r);
sleep(1);
}
close(fd);
unlink(FIFO_SERVER);
}
//pr----x--t 1 qust qust 0 2012-07-01 14:05 myfifo
在Linux系统中FIFO的类型用p表示。固然FIFO文件存在于文件系统中(可供不同的进程打开),但FIFO中的内容都存放在内存中,所以文件大小始终为0。