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?
I doubt that you conducted the above experiment with the shown result, because that would not be standard-conforming - cf. dup:
So, after the shown code sequence,
newfd
must be not1
, but rather-1
, anderrno
EBADF
.Just a tip about "duplicating standard output".
On some Unix Systems (but not GNU/Linux)
it is equivalent to: