最近我在一次工作面试中被问到这个问题。我诚实地说,我知道符号链接的行为和如何创建一个,但不了解硬链接的使用,以及它与符号链接的区别。


当前回答

在进行增量备份时,硬链接非常有用。例如,请参阅rsnapshot。这个想法是使用硬链接进行复制:

拷贝备份号n到n + 1 拷贝备份n - 1到n ... 拷贝备份0到备份1 用任何更改过的文件更新备份0。

除了您所做的任何更改之外,新的备份不会占用任何额外的空间,因为所有增量备份都将指向未更改的文件的同一组inode。

其他回答

当原始文件被移动时,硬链接非常有用。例如,将文件从/bin移动到/usr/bin或/usr/local/bin。到/bin中文件的任何符号链接都将被破坏,但是硬链接(直接到文件的inode的链接)不会关心。

硬链接可能占用更少的磁盘空间,因为它们只占用一个目录条目,而符号链接需要自己的inode来存储它所指向的名称。

Hard links also take less time to resolve - symlinks can point to other symlinks that are in symlinked directories. And some of these could be on NFS or other high-latency file systems, and so could result in network traffic to resolve. Hard links, being always on the same file system, are always resolved in a single look-up, and never involve network latency (if it's a hardlink on an NFS filesystem, the NFS server would do the resolution, and it would be invisible to the client system). Sometimes this is important. Not for me, but I can imagine high-performance systems where this might be important.

I also think things like mmap(2) and even open(2) use the same functionality as hardlinks to keep a file's inode active so that even if the file gets unlink(2)ed, the inode remains to allow the process continued access, and only once the process closes it does the file really go away. This allows for much safer temporary files (if you can get the open and unlink to happen atomically, which there may be a POSIX API for that I'm not remembering, then you really have a safe temporary file) where you can read/write your data without anyone being able to access it. Well, that was true before /proc gave everyone the ability to look at your file descriptors, but that's another story.

说到这里,恢复一个在进程a中打开,但在文件系统中未链接的文件需要使用硬链接来重新创建inode链接,这样当打开该文件的进程关闭或离开时,该文件不会消失。

硬链接和软链接可以很容易地用这张图来解释。

在这个答案中,当我说文件时,我指的是内存中的位置

所有保存的数据都使用称为inode的数据结构存储在内存中,每个inode都有一个inodennumber。inode号用于访问inode。到文件的所有硬链接可能有不同的名称,但共享相同的inode号。因为所有的硬链接都有相同的inodennumber(访问相同的inode),所以它们都指向相同的物理内存。

符号链接是一种特殊的文件。因为它也是一个文件,它将有一个文件名和一个inode号。如上所述,inode号访问指向数据的inode。现在,符号链接的特殊之处在于,符号链接中的inodennumbers访问那些指向另一个文件的“路径”的inode。更具体地说,符号链接中的inode号访问指向另一个硬链接的inode。

当我们在GUI中移动、复制、删除文件时,我们使用的是文件的硬链接,而不是物理内存。当我们删除一个文件时,我们正在删除该文件的硬链接。我们并没有清除物理内存。如果文件的所有硬链接都被删除,那么将无法访问存储的数据,尽管它可能仍然存在于内存中

在文件系统下面,文件由inode表示。(或者是多个索引节点?不确定。)

文件系统中的文件基本上是一个到inode的链接。 因此,硬链接只是创建另一个文件,该文件具有指向相同底层inode的链接。

当您删除一个文件时,它会删除到底层inode的一个链接。只有当到inode的所有链接都被删除时,inode才会被删除(或可删除/可覆盖)。

符号链接是指向文件系统中另一个名称的链接。

一旦建立了硬链接,链接就指向inode。删除、重命名或移动原始文件不会影响硬链接,因为它链接到底层inode。对inode上数据的任何更改都反映在引用该inode的所有文件中。

注意:硬链接只在同一个文件系统内有效。符号链接可以跨文件系统,因为它们只是另一个文件的名称。

我对使用的两点看法:

软链接可以用来缩短长路径名,例如:

ln -s /long/folder/name/on/long/path/file.txt /short/file.txt

对/short/file.txt所做的更改将应用于原始文件。

硬链接可以用来移动大文件:

$ ls -lh /myapp/dev/
total 10G
-rw-r--r-- 2 root root 10G May 22 12:09 application.bin

ln /myapp/dev/application.bin /myapp/prd/application.bin

即时复制到不同的文件夹,原始文件(在/myapp/dev上)可以移动或删除,而不会触及/myapp/prd上的文件