Linux 硬链接与软链接

在 Linux 中一切皆文件。文件由两部分组成:用户数据(user data)和元数据(meta data)。用户数据就是文件数据块(data block),文件数据块是实际存放文件数据的地方。元数据包含文件大小、创建时间、inode 号等信息。inode 号相当于 C 中的指针,是文件的唯一标识,系统通过 inode 号查找文件数据块,文件名只是为了方便人们记忆和使用。

硬链接是指通过索引节点进行链接。比如 A 是 B 的硬链接,则 A 与 B 的 inode 号相同,也就是说 A 与 B 是共享同一个文件数据块,删除 A 或者 B 对数据没有影响。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
gax@security:~/test$ touch file && echo 'this is a test file' > file
gax@security:~/test$ ln file hard
gax@security:~/test$ ls -li
总用量 8
1574700 -rw-rw-r-- 2 gax gax 20 3月 31 12:23 file
1574700 -rw-rw-r-- 2 gax gax 20 3月 31 12:23 hard
gax@security:~/test$ cat hard
this is a test file
gax@security:~/test$ echo 'hard add something' >> hard
gax@security:~/test$ cat file
this is a test file
hard add something
gax@security:~/test$ rm file
gax@security:~/test$ cat hard
this is a test file
hard add something
gax@security:~/test$ ls -li
总用量 4
1574700 -rw-rw-r-- 1 gax gax 39 3月 31 12:24 hard

第二行创建file的硬链接,由第5和6可以看出,两个文件的inode号都是1574700,第三列的2表示inode数目。由以上可以看出,两个文件对于文件系统来说是平等的,两个文件都可以修改文件内容,因为本质上它们指向同一个文件数据块,删除硬链接并不会影响另一个的访问。同时删除硬链接和原文件,真个文件才会真正被删除。

硬链接的特性:

  • 硬链接具有相同的 inode 号,但是不同的文件名
  • 只能对已有文件创建
  • 不能跨文件系统创建
  • 不能对目录创建
  • 删除一个硬链接文件并不影响其他有相同 inode 号的文件

软链接相当于 Windows 中的快捷方式,软链接的出现比快捷方式早很多年。与硬链接不同,软链接inode号与原文件不同,软链接具有自己的inode号以及独立的文件数据块,数据块中存放的内容是另一文件的路径。

1
2
3
4
5
6
7
8
9
10
11
12
13
gax@security:~/test$ touch file && echo 'this is a test file' > file
gax@security:~/test$ ls -li
总用量 4
1574700 -rw-rw-r-- 1 gax gax 20 3月 31 12:49 file
1574701 lrwxrwxrwx 1 gax gax 4 3月 31 12:48 soft -> file
gax@security:~/test$ echo 'soft add something' >> soft
gax@security:~/test$ cat file
this is a test file
soft add something
gax@security:~/test$ rm file
gax@security:~/test$ ls -li
总用量 0
1574701 lrwxrwxrwx 1 gax gax 4 3月 31 12:48 soft -> file

软链接的特性:

  • 软链接有自己的文件属性和权限
  • 可对文件或目录创建
  • 可跨文件系统创建
  • 创建软链接,链接计数不会增加
  • 若软链接指向的文件被删除,该软链接被成为死链接,若文件被重新创建,可恢复正常链接

总结

硬链接:与普通文件没什么不同,inode 都指向同一个文件在硬盘中的区块。

软链接: 保存了其代表的文件的绝对路径,是另外一种文件,在硬盘上有独立的区块,访问时替换自身路径。

详细的比较可以参考第一个链接。

参考资料

理解 Linux 的硬链接与软链接

理解 inode - 阮一峰的网络日志

赞赏是对作者最大的支持!
0%