Linux 文件系统

来源:互联网 发布:sqlserver完全卸载 编辑:程序博客网 时间:2024/06/05 12:43


         在文件系统内部,目录是一个包含文件名与i-节点对的列表的文件。   i-节点记录文件属性,入大小、文件所有者和最近修改时间等信息。所有的i-节点都有相同的大小,

并且i-节点表是这些结构的一个列表。文件系统的每个文件在该表中都有一个i-节点。

         文件在目录中的含义是目录中存放文件在i-节点表的入口,而文件的内容则存储在数据区。

         创建一个新文件主要包括4个步骤:

        (1)存储属性:内核先找到一个空的i-节点。把文件信息写入其中。

        (2)存储数据:把数据写入存储块里。

        (3)记录分配情况:内核在i-节点的磁盘分布区记录了块序列的编号。

        (4)添加文件名到目录:内核将入口添加到目录文件。文件名和i-节点的对应关系将文件名和文件的内容及属性链接了起来。

           目录是一种包含了i-节点号和文件名的表,树形结构。

内核在每个目录都设置一个指向目录本身的i-节点的入口,这个入口被称为".",用以使上级目录记录这个i-节点,从而实现子目录链接

目录包含一个".."的入口。是父目录的保留名字。

$ pwd
用来显示到达当前目录的路径。
工作过程

(1)得到"."的i-节点号,称其为n。

(2)chdir..

(3)找到i-节点号n链接的名字

重复直到到达树的顶端。

如何知道到达了树的顶端?在一个Unix文件系统的根目录中,"."和".."指向同一个i-节点。

/*** spwd.c: a simplified version of pwd** starts in current directory and recursively* climbs up to root of filesystem, prints top* part then prints current part** uses readdir() to get info about each thing** bug: prints an empty string if run from "/"*/#include<stdio.h>#include<sys/types.h>#include<sys/stat.h>#include<dirent.h>void printpathto(ino_t this_inode);void inum_to_name(ino_t inode_to_find, char *namebuf, int buflen);ino_t get_inode(char *fname);int main(void){printpathto(get_inode(".") );   // print path to hereputchar('\n');return 0;}/*** prints path leading down to an with this inode* kindof recursive*/void printpathto(ino_t this_inode){ino_t my_inode;char its_name[BUFSIZ]; if(get_inode("..") != this_inode){chdir("..");                               // up one dirinum_to_name(this_inode, its_name, BUFSIZ);// get its namemy_inode = get_inode(".");                 // print headprintpathto(my_inode);                      // recursivelyprintf("/%s", its_name); // now print name of this}}/*** looks through current directory for a file with this inode* number and copies its name into namebuf*/void inum_to_name(ino_t inode_to_find, char *namebuf, int buflen){DIR *dir_ptr;            // the directorystruct dirent *direntp;  // each entrydir_ptr = opendir(".");if(dir_ptr == NULL){perror(".");exit(1);}/* search directory for a file specified inum  */while((direntp = readdir(dir_ptr)) != NULL){if(direntp->d_ino == inode_to_find){strncpy(namebuf, direntp->d_name, buflen);namebuf[buflen - 1] = '\0';closedir(dir_ptr);return;}}fprintf(stderr, "error looking for inum %d\n", inode_to_find);exit(1);}/*** returns inode number of the file*/ino_t get_inode(char *fname){struct stat info;if(stat(fname, &info) == -1){fprintf(stderr, "Cannot stat ");perror(fname);exit(1);}return info.st_ino;}

参考《Unix/Linux编程实践教程》

0 0
原创粉丝点击