open() what happens if I open twice the same file?

To complement what @Drew McGowen has said,

In fact, in this case, when you call open() twice on the same file, you get two different file descriptors pointing to the same file (same physical file). BUT, the two file descriptors are indepedent in that they point to two different open file descriptions(an open file description is an entry in the system-wide table of open files).

So read operations performed later on the two file descriptors are independent, you call read() to read one byte from the first descriptor, then you call again read()on the second file descriptor, since thier offsets are not shared, both read the same thing.

#include <fcntl.h>

int main()
{
  // have kernel open two connection to file alphabet.txt which contains letters from a to z
  int fd1 = open("alphabet.txt",O_RDONLY);
  int fd2 = open("alphabet.txt",O_RDONLY);


  // read a char & write it to stdout alternately from connections fs1 & fd2
  while(1)
  {
    char c;
    if (read(fd1,&c,1) != 1) break;
    write(1,&c,1);
    if (read(fd2,&c,1) != 1) break;
    write(1,&c,1);
  }

  return 0;
}

This will output aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz

See here for details, especially the examples programs at the end.


It will create a new entry in the file descriptor table and the file table. But both the entries (old and new) in the file table will point to the same entry in the inode table.


In this case, since you're opening both files as read-only, you will get two different file descriptors that refer to the same file. See the man page for open for more details.