"dup" function, "more" and redirect
I have a problem with this little code for educational purposes. I don't understand how it works.
#include <stdio.h>
#include <fcntl.h>
#define FNAME "info.txt"
#define STDIN 0
int main(){
int fd;
fd = open(FNAME, O_RDONLY);
close(STDIN); //entry 0 on FDT is now free
dup(fd); //fd duplicate is now stored at entry 0
execlp("more","more",0);
}
By running this program, it will print the contents of the "info.txt" file to the terminal. I do not understand why! Where is the relationship between "more" and STDIN (keyboard or file)?
Why if I use no more arguments and don't redirect to a file, it just shows the help screen, but the redirect redirect uses the file as input?
dup
always gives you the lowest file descriptor number available.
By default, all processes will have 0
, 1
and 2
for stdin
, stdout
and stderr
. You open a file from which you will get the file descriptor value 3
. After that you closed stdin
. Now calling dup
after that will give you the lowest available value as a duplicate file descriptor for 3
, so you will get stdin
as a 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 that's why its displaying the contents of a file, the command more
can be used in two ways.
- more filename
- team | more
In your exec, you do not specify filename
as a command line argument to the command more
. So it is executed in mode pipe
by reading it from stdin.