有人可以解释用C做什么DUP()? [英] Can someone explain what dup() in C does?
问题描述
我知道DUP,dup2,dup3的创建文件描述符的副本oldfd 的(从手册页)。但是我不能消化它。
I know that dup, dup2, dup3 "create a copy of the file descriptor oldfd"(from man pages). However I can't digest it.
据我所知文件描述符只是数字以跟踪文件的位置和他们的方向(输入/输出)。那岂不是更容易只是
As I know file descriptors are just numbers to keep track of file locations and their direction(input/output). Wouldn't it be easier to just
fd=fd2;
当我们要复制一个文件描述符?
Whenever we want to duplicate a file descriptor?
和别的东西。
DUP()使用的新的描述符的编号最小的未使用的描述符。的
这是否意味着它也可以作为价值的标准输入的标准输出或标准错误的,如果我们假设我们有关闭( )的-ed其中之一?
Does that mean that it can also take as value stdin, stdout or stderr if we assume that we have close()-ed one of those?
推荐答案
只是想尝试了一下后,对自己回应关于第二个问题。
Just wanted to respond to myself on the second question after experimenting a bit.
答案是是即可。您所做的文件描述符可以采取值为0,1,2,如果标准输入,标准输出或标准错误被关闭。
The answer is YES. A file descriptor that you make can take a value 0, 1, 2 if stdin, stdout or stderr are closed.
例如:
close(1); //closing stdout
newfd=dup(1); //newfd takes value of least available fd number
如果发生这种情况,文件描述符:
Where this happens to file descriptors:
0 stdin .--------------. 0 stdin .--------------. 0 stdin
1 stdout =| close(1) :=> 2 stderr =| newfd=dup(1) :=> 1 newfd
2 stderr '--------------' '--------------' 2 stderr
这篇关于有人可以解释用C做什么DUP()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!