Can someone explain what dup() in C does?

Pithikos picture Pithikos · Oct 22, 2011 · Viewed 34.7k times · Source

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?

And something else..

dup() uses the lowest-numbered unused descriptor for the new descriptor.

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?

Answer

Pithikos picture Pithikos · Oct 24, 2011

Just wanted to respond to myself on the second question after experimenting a bit.

The answer is YES. A file descriptor that you make can take a value 0, 1, 2 if stdin, stdout or stderr are closed.

Example:

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