dup() call
man page
$ man 2 dup
int dup2(int oldfd, int newfd);
dup2()
The dup2() system call performs the same task as dup(), but
instead of using the lowest-numbered unused file descriptor, it
uses the file descriptor number specified in newfd. In other
words, the file descriptor newfd is adjusted so that it now
refers to the same open file description as oldfd.
Linux 2021-03-22 DUP(2)
$ man 2 dup
int dup2(int oldfd, int newfd);
dup2()
dup2() makes newfd be the copy of oldfd, closing newfd first if necessary, but note the following:
Linux 2012-02-14 DUP(2)
Writing redirection case
In the case of using pre-hunted descriptor like pipe, set it as oldfd and stdout as newfd.
The principal of thought is, the value itself is unchangeable.
The description of the dup() function is often wrote as copy the file descriptor, but it's not clear to be understood.
The dup's arguments are fixed values, but the function of the old value is copied to new one, so that new value itself has the same behavior as old one.
example
Let't assume that we've got 5 as pipe writing target fd.
Then to be is
dup2(5, 1);
1 is reserved as global stdout fd, but dup2() closes 1 and make the number itself working as 5.
The most important is the function of original fd oldfd, i.e 5.
We want to make 1 behaves as the same as 5.
So at first, function side value is reserved, then mimicking side value is specified.
Typical usage of execve() redirecting.
We cannot stop execve() putting their contents to 1 (i.e stdout), but 1 itselves behavior is changeable by the call of dup().
TODO
How to do the same as above with dup(oldfd) ?
dup() returns new file descriptor value by itself. It means the value cannot be specified.
So pre-hunted pipe value is not usable in this scenario.