Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top