读书人

read在非拥塞下模式下没有数据 不返回

发布时间: 2013-10-14 12:54:46 作者: rapoo

read在非堵塞下模式下没有数据 不返回-1
在man中有一行这么写着:


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].


也就是 如果是非堵塞的读在没有数据的时候 应该是要返回-1并且把errno设置成EAGAIN的才对

但是在实际使用中 发现并不会返回-1 反而只是单单返回个0 并且errno也没被设置
代码如下:

#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);
}

实验时 tmp/cctemp这个文件是存在的但是并没有内容
启动reader:

[root@localhost fifo]# reader
等待数据进入.0...
Success
等待数据进入.0...
Success
等待数据进入.0...
Success
等待数据进入.0...
Success
等待数据进入.0...
Success
等待数据进入.0...
Success

发现在没有数据的情况下(如果把以上的O_NONBLOCK取消掉 会堵塞住) 他并不会返回-1

虽然实际使用没什么大问题 但还是觉得有点奇怪 望解答 c
[解决办法]
说明数据未准备好。
[解决办法]
a file (other than a pipe or FIFO) that supports non-blocking
是否理解错了啊, 这个的意思是说 一个支持非阻塞的文件 那么你的 /tmp/cctemp 支持非阻塞的读么
[解决办法]
引用:
Quote: 引用:

a file (other than a pipe or FIFO) that supports non-blocking
是否理解错了啊, 这个的意思是说 一个支持非阻塞的文件 那么你的 /tmp/cctemp 支持非阻塞的读么

我的/tmp/cctemp是FIFO啊...这句话的意思怎么理解好呢...
是FIFO不会发生这个情况??

a file (other than a pipe or FIFO) that supports non-blocking
这个的意思是::::一个支持非阻塞读的文件(除了管道或者FIFO)
你的/tmp/cctemp是FIFO 所以。。
[解决办法]
楼上正解。。。。

读书人网 >UNIXLINUX

热点推荐