一个关于dup2的问题

在许多程序中都包含下面一段代码:

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.


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值