Talking about hard links and soft links in Linux

Foreword: The storage method of memory in Linux is different from that in Windows. This is the most basic small problem for learning Linux. If you don't understand this, you can only say that you don't know enough about Linux.

What is a link?

A link is a way of creating a connection between a shared file and several directory items of the user who accesses it.

When we talk about hard links and soft links, let's talk about hard disk storage first.

for hard disk storage

As shown in the figure, the hard disk is divided into metadata part and data part

A good understanding of data is to store your data, so what is metadata? Metadata , you can understand that this thing is an index. When you want to find data, you need to find the head address of the location you want to find data in the metadata, and then go to the data after getting the head address part to find stored data.

Take the USB flash drive we bought as an example. When you buy a 128G USB flash drive, you plug it into the computer and find that it is not 128G, maybe only 117G. So where did the more than 10G go? In fact, the 10G is allocated to metadata part.

Next, let's talk about hard links

A hard link is a pointer to an inode (what we call a "key"). The system does not reallocate inodes for them, the two files have the same inode. Create a hard link with the ln command.

Hard link files have the following two limitations:

  • Allow creating hard links to directories

  • Links can only be created between files in the same file system

Suppose we have a file q.txt, and the data has been stored in the data part. If we want to access the data, we get the "key" in the metadata through q.txt and go to the data part to find the corresponding data. When we If a hard link is established, then link.txt also points to the "key" pointed to by q.txt, no new inode is created, and no hard disk space is occupied (advantages) .

When we delete a file, we don’t actually clear the stored data, but just cut off the entry to query the data. When we establish a hard link, we delete q.txt as shown in the figure below .

At this point we can still access the data through link.txt.

Let's talk soft links

对于软链接我们对他并不陌生,可能你会说自己没有听说过软链接,那只是你没有了解他的名字,但是你一直再用这个链接,在Windows系统中,我们用类似软链接的形式,那些所谓的快捷方式就是“软链接”,我们应该删除过文件,没错,当我们把源文件删除后(其实就是删除了入口),我们采用的软链接就不能再访问文件数据了。

软链接也叫符合链接,这个文件包含了另一个文件的路径名。可以任意文件或目录。

软链接图示

软链接与硬链接不同,他们不公用一个“钥匙”,而是再元数据那新建了一个inode(我所称的“钥匙”),如图,红色的小点就是。当我们采用p.txt来访问数据的时候,过程:从p.txt在元数据找到inode,这个里面指向q.txt,如何在从q.txt去元数据那找到“钥匙”,然后去数据那去找存储的数据。

当我们删除掉源文件q.txt

q.txt指向“钥匙”的链接断了,所以我们用p.txt就没法在访问数据了。

实例

接下来我们在centos7里面进行操作一波,这个软硬链接。

硬链接

我们先来一个硬链接,创建一个空文档,在里面写入一句代码,然后对他创建硬链接。

创建空文档:touch 文件名,进去文档写:vim 文件名,创建硬链接:ln 文件名 新文件名

先创建然后从硬链接访问,删除源文件然后再用硬链接还可以继续访问

软链接

同样创建一个空文档,建立一个软链接:ln -s 文件名 新文件名

看完这些估计应该对这有了了解,鄙人不才,如有不对的地方清多多指教。

Guess you like

Origin blog.csdn.net/qq_61897141/article/details/129629698