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.