dup
always gives you the lowest available file descriptor number.
By default all process will have 0
, 1
and 2
for stdin
, stdout
and stderr
. You are opening a file from that you will get a file descriptor value 3
. After that you have closed stdin
. Now calling dup
after that will give you a lowest available value as a duplicate file descriptor for 3
, so you will be getting stdin
as duplicate file descriptor for 3
.
int main()
{
int fd, fd2;
fd = open(FNAME, O_RDONLY); //This will be 3
fd2 = dup(fd); //This will be 4 because 4 is the lowest available value
close(STDIN); //entry 0 on FDT is now free
dup(fd); //fd duplicate is now stored at entry 0
execlp("more","more",0);
}
And here why its displaying the content of the file is, more
command can be used in two ways.
- more filename
- command | more
In your exec, you are not giving any filename
as command line argument for more
command. So its executing in pipe
mode, by reading it from stdin.