当前位置: 技术问答>linux和unix
unix环境高级编程中一个习题的疑问
来源: 互联网 发布时间:2016-06-23
本文导语: 题目: 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, ass...
题目:
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.
看答案的意思难道指向同一个文件表项的文件描述符个数有限制么?
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.
看答案的意思难道指向同一个文件表项的文件描述符个数有限制么?
|
没有限制,只是网络程序(比如inetd)通常会这么用, 比如inetd启动telnetd时。
|
我曾经在网上搜过相关的答案,有两个原因。你可以参考吧,毕竟只是一个习题。首先是为了节约文件描述符,最后一句话表明了,不是有无限制,是没必要。二是为了防止关闭0.1,2等标准输出,输入,出错描述符。所以要判断是否大于2.
您可能感兴趣的文章:
本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。