我们知道inode索引节点是UNIX操作系统的一种数据结构,它包含了与文件系统中各个文件相关的一些重要信息,当用户搜索一个文件时,操作系统会根据文件名在磁盘上的inode表中找到该文件对应的inode,该inode包含文件的属主ID,属主的组ID,文件大小,文件使用磁盘块数量,修改时间等信息。但是在实际操作中,操作系统操作的都是内存上的内容,所以内存中会有磁盘上部分的inode表中的数据或者叫做inode表的一个缓存,用于对inode的快速访问,内存中的这块inode叫做内存inode。
系统文件打开表(Open file table)存在于内存中,整个操作系统只维护一张这样的表,用于保存已经打开文件的FCB文件号、共享计数(打开共享)、读写位置、打开模式、修改标志等信息,其中还有一个比较重要的属性就是一个指向内存inode的一个指针,这个指针的作用我们后面会介绍。
用户文件打开表(File Descriptor table)是每个进程都有的一张表,用于记录用户打开的文件的一些信息,主要的属性有文件描述符fd和 一个指向系统文件打开表项的指针。
用户文件打开表、系统文件打开表和内存inode的关系如下
在同一个进程中共享同一个open file table表项,结果是两个文件共享一个句柄,可以dup()实现。
#include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> int main(){ int fd = open("test.txt",O_RDONLY); int fdcopy = dup(fd); char buff1[10]; char buff2[10]; read(fd, buff1, 5); read(fdcopy, buff2, 5); printf("buff1:%s\n", buff1); printf("buff2:%s\n", buff2); close(fd); close(fdcopy); }其中test.txt中的数据是:
ABCDEFGHIJ结果:
buff1:ABCDE buff2:FGHIJ父进程通过fork命令实现子进程对父进程的一种复制,该父子进程的用户文件打开表一样。
#include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> int main(){ int fd = open("test.txt",O_RDONLY); pid_t pid = fork(); char buff[10]; if(pid > 0){ read(fd, buff, 5); printf("father:%s\n", buff); } else{ read(fd, buff, 5); printf("son:%s\n", buff); } }结果:
father:ABCDE son:FGHIJ两个进程访问同一个文件,但是其系统文件打开表指向不同。代码和上面的跨进程复制fd几乎一样,只是这个open函数在fork函数之后执行,导致两个进程file ptr分别指向系统文件打开表不同位置。
#include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> int main(){ pid_t pid = fork(); int fd = open("test.txt",O_RDONLY); char buff[10]; if(pid > 0){ read(fd, buff, 5); printf("father:%s\n", buff); } else{ read(fd, buff, 5); printf("son:%s\n", buff); } }结果:
father:ABCDE son:ABCDE同一个进程操作同一文件,但是对应的系统文件打开表表项不一样。
int main(){ int fd1 = open("test.txt",O_RDONLY); int fd2 = open("test.txt", O_RDONLY); char buff1[10]; char buff2[10]; read(fd1, buff1, 5); read(fd2, buff2, 5); printf("buff1:%s\n", buff1); printf("buff2:%s\n", buff2); close(fd1); close(fd2); }结果:
buff1:ABCDE buff2:ABCDE