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?
Let's say you're writing a shell program and you want to redirect stdin and stdout in a program you want to run. It could look something like this:
dup2() is a little more convenient way to do it the close() dup() can be replaced by:
The reason why you want to do this is that you want to report errors to stdout (or stderr) so you can't just close them and open a new file in the child process. Secondly, it would be a waste to do the fork if either open() call returned an error.
dup() and dup2() system call
•The dup() system call duplicates an open file descriptor and returns the new file descriptor.
•The new file descriptor has the following properties in common with the original file descriptor: 1. refers to the same open file or pipe. 2. has the same file pointer -- that is, both file descriptors share one file pointer. 3. has the same access mode, whether read, write, or read and write.
• dup() is guaranteed to return a file descriptor with the lowest integer value available.It is because of this feature of returning the lowest unused file descriptor available that processes accomplish I/O redirection.
int dup(file_descriptor)
int dup2(file_descriptor1, file_descriptor2)
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:
Where this happens to file descriptors:
see this page, stdout can be aliased as
dup(1)
...The single most important thing about dup() is it returns the smallest integer available for a new file descriptor. That's the basis of redirection:
After this anything written to file descriptor 1 (stdout), magically goes into "file".
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.