unix环境高级编程中一个习题的疑问

J_X_Q 2009-08-12 09:20:05
题目:
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.

看答案的意思难道指向同一个文件表项的文件描述符个数有限制么?
...全文
81 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
happyangel_xl 2009-08-12
  • 打赏
  • 举报
回复
我曾经在网上搜过相关的答案,有两个原因。你可以参考吧,毕竟只是一个习题。首先是为了节约文件描述符,最后一句话表明了,不是有无限制,是没必要。二是为了防止关闭0.1,2等标准输出,输入,出错描述符。所以要判断是否大于2.
J_X_Q 2009-08-12
  • 打赏
  • 举报
回复
To mymtom:
为什么啊?有这样做的理由么?
ShowMan 2009-08-12
  • 打赏
  • 举报
回复
一个例子而已。
mymtom 2009-08-12
  • 打赏
  • 举报
回复
没有限制,只是网络程序(比如inetd)通常会这么用, 比如inetd启动telnetd时。

23,116

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧