-1

Here is my program: I am confused about it. I don't understand why c1 and c2 share the same value, but c3's value is different from c1 and c2's? Can someone help me explain it? Thank you. Here is the program:

#include <stdio.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
 int fd1, fd2, fd3;
 char c1, c2, c3;
 char *fname = argv[1];
 fd1 = open(fname, O_RDONLY, 0);
 fd2 = open(fname, O_RDONLY, 0);
 fd3 = open(fname, O_RDONLY, 0);
 dup2(fd2, fd3);
 read(fd1, &c1, 1);
 read(fd2, &c2, 1);
 read(fd3, &c3, 1);
 printf("c1 = %c, c2 = %c, c3 = %c\n", c1, c2, c3);
 return 0;
} 
user144600
  • 529
  • 2
  • 7
  • 18
  • 3
    Did you read the docs for `dup2`? What didn't you understand about it? – Mat Sep 27 '15 at 19:25
  • I mean after calling dup2, the fd2 and fd3 should point to the same file in the open file table,then I think c2 and c3 should share the same value instead of c1 and c2 – user144600 Sep 27 '15 at 19:29

1 Answers1

2

After calling dup2, fd2 is equivalent to fd3, so what happens is:

read(fd1, &c1, 1);

You read the 1st char of the file

read(fd2, &c2, 1);

Since fd2 is independent of fd1, it still is at the beginning of the file, so you read the 1st char of the file again

read(fd3, &c3, 1);

Since fd3 is equivalent to fd2 after the dup2, you've already read the 1st char of the file with it when you called read(fd2, &c2, 1); so now it reads the 2nd char in the file.

That's why the first 2 are the same, cause they're the 1st char in the file, and the 3rd one is different as it is the 2nd char in the file.

Fabio
  • 3,015
  • 2
  • 29
  • 49