一个关于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.


原创粉丝点击