Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 592
sdafad Avatar asked Jun 27 '13 21:06

sdafad


People also ask

Can a file be opened twice?

Risk Assessment. Simultaneously opening a file multiple times can result in unexpected errors and nonportable behavior.

What happens if you open a file twice in Python?

The same file can be opened more than once in the same program (or in different programs). Each instance of the open file has its own file pointer that can be manipulated independently.

Can a file be opened twice using same stream?

You can definitely open a file for reading more than once, either in the same program, or in different programs. It should have no effect on the program(s).

What does the open () returns on?

The open() function opens a file, and returns it as a file object. Read more about file handling in our chapters about File Handling.


1 Answers

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.

like image 57
Gab是好人 Avatar answered Sep 28 '22 17:09

Gab是好人