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

本秂侑毒 提交于 2019-12-05 09:47:28

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!