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

泪湿孤枕 提交于 2019-12-07 06:28:55

问题


If I open the same file twice, will it give an error, or will it create two different file descriptors? For example

a = open("teste.txt", O_RDONLY);
b = open("teste.txt", O_RDONLY);

回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/17353461/open-what-happens-if-i-open-twice-the-same-file

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