Linux文件系统中的链接


 

•     inode

     在讨论Linux系统的链接之前,不得不先说下inode。Linux文件系统中的每一个对象都有唯一的inode索引,每一个inode号和文件系统的一个对象一一对应,要查看文件或目录的inode号可在ls命令中使用-i选项,每个目录下的.(当前目录)和..(上级目录)都是硬链接。如下面例子:

root@vrlab726-desktop:~/Desktop# pwd

/root/Desktop

root@vrlab726-desktop:~/Desktop# ls -ial

total 8672

6447440 drwxr-xr-x  9 root     root        4096 2011-12-14 19:27 .

复制代码

     目录/root/Desktop的inode号为6447440,下面再看下/root/Desktop/test/..的inode号:

root@vrlab726-desktop:~/Desktop# cd test

root@vrlab726-desktop:~/Desktop/test# pwd

/root/Desktop/test

root@vrlab726-desktop:~/Desktop/test# ls -ial

total 8

7668672 drwxr-xr-x 2 root root 4096 2011-12-14 19:27 .

6447440 drwxr-xr-x 9 root root 4096 2011-12-14 19:27 ..

复制代码

      从中可以发现二者的inode号完全一样,即两者链接到物理磁盘上的同一个条目。

•     硬链接

      一个inode号可以和任意多个硬链接对应,当所有硬链接都删除后,此inode号也将由系统自动删除,ls -ial命令的第三列即为和当前inode号关联的硬链接数目。创建硬链接的命令为:

root@vrlab726-desktop:~/Desktop/test# touch file

root@vrlab726-desktop:~/Desktop/test# echo "helloWorld" > file

root@vrlab726-desktop:~/Desktop/test# more file

helloWorld

root@vrlab726-desktop:~/Desktop/test# ln file fileHardLink

root@vrlab726-desktop:~/Desktop/test# ls -ial

total 16

7668672 drwxr-xr-x 2 root root 4096 2011-12-14 20:19 .

6447440 drwxr-xr-x 9 root root 4096 2011-12-14 19:27 ..

7668707 -rw-r--r-- 2 root root   11 2011-12-14 20:19 file

7668707 -rw-r--r-- 2 root root   11 2011-12-14 20:19 fileHardLink

复制代码

      从中可以看出硬链接都指向了同一个inode条目,因此所占用的空间相同。然而,Linux系统中的硬链接有两个限制:1.硬链接只能链接到文件,而不能链接到文件夹。尽管.和..是系统创建的链接到目录的硬链接,但不允许用户(即使是root账户)创建链接到目录的硬链接。2.硬链接不能跨文件系统。

•     软链接(符号链接)

      实际上,软链接比硬链接更为常用,符号链接是一种特殊的文件类型,它只是通过文件名链接到另一个文件,而不是直接链接到inode。如果链接的目标文件被删除了,那么会导致链接到该目标文件的所有软链接断开,不再可用。创建软连接的命令如下:

root@vrlab726-desktop:~/Desktop/test# ln -s file fileSoftLink

root@vrlab726-desktop:~/Desktop/test# ls -ial

total 16

7668672 drwxr-xr-x 2 root root 4096 2011-12-14 20:25 .

6447440 drwxr-xr-x 9 root root 4096 2011-12-14 19:27 ..

7668707 -rw-r--r-- 2 root root   11 2011-12-14 20:19 file

7668707 -rw-r--r-- 2 root root   11 2011-12-14 20:19 fileHardLink

7668708 lrwxrwxrwx 1 root root    4 2011-12-14 20:25 fileSoftLink -> file

复制代码

      可以从两方面辨别出符号链接,ls -ial的第二列中第一个字母为l;在最后一列中的目标文件前有->符号。

 

总结: www.2cto.com

      硬链接基于inode实现,而软链接基于名称(或路径)实现;硬链接只允许用户创建链接到文件的硬链接,而软链接既可链接到文件又可链接到目录;硬链接不允许跨文件系统(因不同文件系统中的inode号可能相同),而软链接由于通过路径实现,所以可以跨文件系统。

  作者 静思者

相关内容

    暂无相关文章