Question

it is my understanding that if i have two file descriptors

int fd1, fd2;

that both of these functions:

dup2(fd1, fd2);

And -

fd1 = dup2(fd1, fd2);

will, in effect, accomplish the same task.

What is the point of dup2() having a return value? and if the return value of dup2() is just the file descriptor, why use dup2 if you can just just say:

fd2 = fd1;

There's clearly something that I'm missing here.

Btw: please don't tell me to read the manpage, or some book that I don't own. That isn't helpful.

Was it helpful?

Solution

What you are missing is that it doesn't copy the variable containing the fd value, it makes a second fd which refers to the same open file as the original fd. These two file descriptors then act independently.

However, one major use of dup2 is to "reopen" a stdio descriptor to an already opened file. For example, to pipe between two child processes, you would first use pipe to create a pipe with two fds. Then, in each child process, dup2 would be used to replace stdin or stdout with one of the pipe fds.

OTHER TIPS

Um .. they are the same function. In the first case you are simply ignoring the return value.

And said return value also can be an error code. Which you would see if you RTFM :D

Also as per TFM

dup2() makes newfd be the copy of oldfd, closing newfd first if necessary
. . .
(caveats left out)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top