I found this code here and have several follow up questions.
#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;
}
- If I open the same file (under the same directory) independently in two processes, will it create two vnode entries? Or it depends on the OS?
// PID 1
int fd1 = open("alphabet.txt",O_RDONLY);
// PID 2
int fd2 = open("alphabet.txt",O_RDONLY);
How does
read()know where is the file? Does C first ask for the vnode entry offd1and return the address of it?Following 2., does
read()create new vnode entry or is it using the same one?
vnodeentries. Thevnodeis a data structure in the kernel that represents a file. If you open the same file twice, either within the same process or in two different processes, you get two different file descriptors. These file descriptors are independent of each other, but they both point to the samevnode.read()function knows the location of the file through the file descriptor. When you callopen(), the operating system returns a file descriptor, which is an integer. This file descriptor is an index into an array in the kernel called the file descriptor table. This table contains the information about all open files, including thevnodeof the file. So whenread()is called with a file descriptor, it looks up the file descriptor table to find thevnodeand thus the location of the file.read()function does not create a newvnodeentry. Thevnodeis created when the file is first opened, and subsequent calls toopen()on the same file will return a new file descriptor pointing to the samevnode. Theread()function only reads data from the file, it does not change thevnodeor the file descriptor table.