日期:2014-05-16 浏览次数:20776 次
When attempting to read a file (other than a pipe or FIFO) that supports non-blocking reads and
has no data currently available:
* If O_NONBLOCK is set, read() shall return -1 and set errno to [EAGAIN].
#include<stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include <unistd.h>
#define FILE_NAME "/tmp/cctemp"
int main(void)
{
int num;
if((num=open(FILE_NAME,O_RDONLY|O_NONBLOCK,0))==-1)
{
printf("打开文件出错 \n");
printf("%m \n",errno);
return -1;
}
char buffer[1024];
int size;
while(1)
{
if((size=read(num,buffer,1024))<=0)
{
printf("等待数据进入.%d...\n",size);
printf("%m \n",errno);
if(errno==EAGAIN)
{
printf("未有数据\n");
}
}else{
printf("接收数据:%s\n",buffer);
memset(buffer,0,sizeof(buffer));
}
sleep(2);
}
unlink(FILE_NAME);
}
[root@localhost fifo]# reader
等待数据进入.0...
Success
等待数据进入.0...
Success
等待数据进入.0...
Success
等待数据进入.0...
Success
等待数据进入.0...
Success
等待数据进入.0...
Success