Unix C dup2 问题 [英] Unix C dup2 Question

查看:29
本文介绍了Unix C dup2 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 dup2() 的问题.它究竟有什么作用?复制文件描述符?

I have a question regarding dup2(). What does it exactly do? Copies the File Descriptor?

我不太明白 dup2() 的用法.我试过谷歌,还是不太明白是什么意思.

I don't quite understand the use of dup2(). I tried Google, and still don't quite understand what it means.

推荐答案

它需要两个作为描述符的参数.它使第二个等同于第一个.除了少数例外情况,您可以互换使用它们……有关用例的更多详细信息,请参阅手册页.

It takes two parameters that are descriptors. It makes the second one equivalent to the first one. You can use them interchangeably with a few minor exceptions... see the man page for more details on the use cases.

您可以这样做,例如,将控制台描述符 1、2 或 3 重定向到某个其他设备或文件.您不想关闭那些然后重新打开的原因是不能保证您将在下一次打开调用中收到相同的数字描述符.这就是为什么您会使用 open() 获取文件描述符,然后使用 dup2(new_descriptor, 1); 强制描述符 1 转到控制台以外的其他地方.

You would do this, for example, to redirect the console descriptors 1, 2, or 3, to some other device or file. The reason you don't want to close those then reopen, is that there is no guarantee you will receive the same number descriptor back in the next open call. That is why you would use open() to get a file descriptor, then dup2(new_descriptor, 1); to force descriptor 1 to go somewhere other than the console.

这篇关于Unix C dup2 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆