3

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?

Fabio Carello
  • 1,062
  • 3
  • 12
  • 30

1 Answers1

4

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.

rashok
  • 12,790
  • 16
  • 88
  • 100
  • I know that. I can not understand why `more` uses the STDIN as input instead of show only the help screen – Fabio Carello Feb 01 '13 at 18:27
  • It checks whether the input is a terminal, and shows help screen if it is. Otherwise it reads stdin, to allow `some commands | more` usage which is fairly common. – Anton Kovalenko Feb 01 '13 at 18:31
  • The "more" command checks if the input is a terminal, and if so says "Sorry, you haven't given me any input". If it's not a terminal [such as in this case, a file], then it goes on and prints the content. – Mats Petersson Feb 01 '13 at 19:08
  • Ok.I t's the same of `more info.txt | more` Thanks raja! – Fabio Carello Feb 02 '13 at 10:24