I have a problem with this little code for educational purposes. I can not 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 starting this program it prints the contents of the file “info.txt” on terminal. I can not understand why! Where is the link between “more” and STDIN (keyboard or file)?
Why if i use more with no args and without redirection on file it just shows a help screen but whit redirection it uses the file as input?
dupalways gives you the lowest available file descriptor number.By default all process will have
0,1and2forstdin,stdoutandstderr. You are opening a file from that you will get a file descriptor value3. After that you have closedstdin. Now callingdupafter that will give you a lowest available value as a duplicate file descriptor for3, so you will be gettingstdinas duplicate file descriptor for3.And here why its displaying the content of the file is,
morecommand can be used in two ways.In your exec, you are not giving any
filenameas command line argument formorecommand. So its executing inpipemode, by reading it from stdin.