一个关于dup2的问题
来源:互联网 发布:最新的社交软件 编辑:程序博客网 时间:2024/06/07 08:59
在许多程序中都包含下面一段代码:
dup2(fd,0);
dup2(fd,1);
dup2(fd,2);
if(fd > 2)
close(fd);
为了说明if语句的必要性,假设fd是1,画出每次调用dup2时3个描述符项及相应的文件表项的变化清。然后再画出fd为3的情况。
答案:如果fd是1,执行dup2(fd ,1)后返回1,但是没有关闭描述符1.调用3次dup2后,3个描述符指向相同的文件表项,所以不需要关闭描述符。
但如果fd是3,调用3次dup2后,有4个描述符指向相同的文件表项,这种情况下就需要关闭描述符3.
if fd is 3, it will close fds 0, 1, 2 which would have been originally pointing to stdin, stdout, stderr respectively, and create 3 copies of fd: 0, 1, 2 all pointing to the same destination as the fd 3. now you don't need 3 so you close it because you already have 0, 1, 2 pointing to where 3 was pointing and you don't plan on using 3 any more.
if fd is 1, it will close fds 0, 2 which would have been originally pointing to stdin, stderr respectively, and create 2 copies of fd: 0, 2 all pointing to the same destination as the fd 1 (stdout). now you do need 1 pointing to stdout because the rest of your program plans on using 1 as stdout, so you don't close fd in that case.
thus you need the if statement because in one case you need to close an fd that you don't plan to use, and in the other case you do not need to close the fd that you do plan to use.
- 一个关于dup2的问题
- 关于dup2重定向STDOUT_FILENO之后的文件缓冲问题
- 关于dup2
- 一个关于dup、dup2 文件描述符重定向函数的程序
- 一个功能类似于dup2() 的函数
- 关于dup2函数
- 写一个与dup2()功能相同的函数
- 编写一个与dup2相同功能的函数!!!
- 关于dup和dup2函数的重定向与还原
- cgi下dup2()问题
- 有关dup2(fd,1),复制文件句柄的问题
- 一个关于Webservices的问题
- 关于类的一个问题
- 关于MVC的一个问题
- 一个关于ASP的问题..
- 一个关于多态性的问题
- 关于.Text的一个问题
- 关于javamail的一个问题
- weblogic 域编译问题
- web.xml 中的listener、 filter、servlet 加载顺序及其详解
- Why do I need to use DAC from Oracle BI?
- Android 3D游戏开发 正交投影视图与透视投影视图
- shp2sqlserver用法
- 一个关于dup2的问题
- gitolite 配置单用户多key
- Android访问权限大全
- PHP设计模式系列 - 解释器模式
- Mediawiki 使用
- mysql concat函数
- 颜色选择表
- c语言运算符号优先级别
- C++关键字volatile解析