免费注册 查看新帖 |

Chinaunix

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

[C] unix环境高级编程中一个习题的疑问 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-08-11 13:43 |只看该作者 |倒序浏览
题目:
The following sequence of code has been observed in various programs:
      dup2(fd, 0);
      dup2(fd, 1);
      dup2(fd, 2);
      if (fd > 2)
          close(fd);
To see why the if test is needed, assume that fd is 1 and draw a picture of what happens to the three descriptor entries and the corresponding file table entry with each call to dup2. Then assume that fd is 3 and draw the same picture.
给出的答案:
If fd is 1, then the dup2(fd, 1) returns 1 without closing descriptor 1. (Remember our discussion of this in Section 3.12.) After the three calls to dup2, all three descriptors point to the same file table entry. Nothing needs to be closed.
If fd is 3, however, after the three calls to dup2, four descriptors are pointing to the same file table entry. In this case, we need to close descriptor 3.

看答案的意思难道指向同一个文件表项的文件描述符个数有限制么?

论坛徽章:
0
2 [报告]
发表于 2009-08-11 14:18 |只看该作者
有限制,但肯定不是3,
这里的意思应该是只保留012,其他的关闭

论坛徽章:
0
3 [报告]
发表于 2009-08-13 01:04 |只看该作者
以前看到过有些程序里面有这段代码,目的是要将012这三个标准设备重定向到fd,完了之后,fd就没有打开的必要,但是在关闭的时候必须检查fd的值,不能close掉012这三个。

论坛徽章:
0
4 [报告]
发表于 2009-08-13 09:31 |只看该作者
问题的关键不在于非得关闭那个fd,而在于如果要关闭,需要判断 fd > 2
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP