免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2057 | 回复: 2
打印 上一主题 下一主题

关于文件描述符和select [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-04-09 11:13 |只看该作者 |倒序浏览
对于套接字来说,当缓冲区中数据多于低潮限度时,套接字为可读,这时使用select函数能够返回正值。
但是对于普通文件描述符来说,它什么时候被标记成可读,或是可写的呢?

我在程序里面用下面的代码,发现fd总是可读的,即FD_ISSET(fd, &readset)总为1,而不管文件a是否为空。不知道是为啥。

    int fd = open("a", O_RDONLY);
    fd_set readset;
    FD_ZERO(&readset);
    FD_SET(fd, &readset);
    int nfds = select(fd + 1, &readset, NULL, NULL, NULL);
    if (nfds == -1)
        return -1;
    if (FD_ISSET(fd, &readset))
        fprintf(stdout, "%d is set\n", fd);

论坛徽章:
11
技术图书徽章
日期:2014-03-01 14:44:34天蝎座
日期:2014-05-21 22:11:59金牛座
日期:2014-05-30 17:06:14
2 [报告]
发表于 2009-04-09 11:50 |只看该作者
Manual说明:
File  descriptors  associated  with  regular files shall always select  true for ready to read, ready to write, and error conditions.

其实也容易理解,select主要处理用可能永远阻塞(管道,终端设备,网络设备)的多路IO,而一般认为磁盘IO只会短时间阻塞
,所以一直都是可读可写,这也同时解释了对普通文件描述符设置O_NONBLOCK是没有必要的。

论坛徽章:
2
2015亚冠之莱赫维亚
日期:2015-09-14 11:19:42操作系统版块每日发帖之星
日期:2015-11-05 06:20:00
3 [报告]
发表于 2009-04-28 09:48 |只看该作者
对普通文件试了下select

    int fd = open("a", O_RDONLY);
    fd_set readset;
    FD_ZERO(&readset);
    FD_SET(fd, &readset);
while(1)
{
    int nfds = select(fd + 1, &readset, NULL, NULL, NULL);
    if(FD_ISSET(fd, &testfds))
    {
        ioctl(fd, FIONREAD, &nread);
        if(nread == 0)
        {
            printf("close file\n");
            close(fd);
            return 0;
        }
    }
}

这里读过1次后 第二次select返回后就退出文件了?
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP