Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain what dup() in C does?

Tags:

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?

like image 585
Pithikos Avatar asked Oct 22 '11 18:10

Pithikos


People also ask

What does dup () do in C?

The dup() system call creates a copy of a file descriptor. It uses the lowest-numbered unused descriptor for the new descriptor. If the copy is successfully created, then the original and copy file descriptors may be used interchangeably.

How is dup used?

dup is used to be able to redirect the output from a process. For example, if you want to save the output from a process, you duplicate the output (fd=1), you redirect the duplicated fd to a file, then fork and execute the process, and when the process finishes, you redirect again the saved fd to output.

What is the difference between dup () and dup2 ()?

The difference between dup and dup2 is that dup assigns the lowest available file descriptor number, while dup2 lets you choose the file descriptor number that will be assigned and atomically closes and replaces it if it's already taken.

What exactly does dup2 do?

The dup2() function duplicates an open file descriptor. Specifically, it provides an alternate interface to the service provided by the fcntl() function using the F_DUPFD constant command value, with fildes2 for its third argument. The duplicated file descriptor shares any locks with the original.


2 Answers

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 
like image 179
Pithikos Avatar answered Sep 22 '22 14:09

Pithikos


A file descriptor is a bit more than a number. It also carries various semi-hidden state with it (whether it's open or not, to which file description it refers, and also some flags). dup duplicates this information, so you can e.g. close the two descriptors independently. fd=fd2 does not.

like image 34
n. 1.8e9-where's-my-share m. Avatar answered Sep 22 '22 14:09

n. 1.8e9-where's-my-share m.