如何分配 inode 编号

Ome*_*gan 4 linux filesystems inode

两个已知事实:

  1. 在 linux 中,将文件从同一文件系统上的一个位置移动到另一个位置不会更改 inode(文件保持在“同一位置”,仅更改了涉及的目录)
  2. 然而,复制会生成一个真正的新文件,带有一个新的 inode。

有了这些信息,我观察到以下现象:

$ ls -li /tmp/*.db
1452722 -rw-r--r-- 1 omerda omerda 245760 Jul  7 12:33 /tmp/vf4.db
$
$ cp /tmp/vf4.db /tmp/vf4.2.db
$ ls -li /tmp/*.db # New inode introduced
1452719 -rw-r--r-- 1 omerda omerda 245760 Jul  7 12:38 /tmp/vf4.2.db
1452722 -rw-r--r-- 1 omerda omerda 245760 Jul  7 12:33 /tmp/vf4.db
$
$ mv /tmp/vf4.2.db /tmp/vf4.db
$ ls -li /tmp/*.db
1452719 -rw-r--r-- 1 omerda omerda 245760 Jul  7 12:38 /tmp/vf4.db
$
$ cp /tmp/vf4.db /tmp/vf4.2.db
$ ls -li /tmp/*.db # Original inode appears again! (1452722)
1452722 -rw-r--r-- 1 omerda omerda 245760 Jul  7 12:41 /tmp/vf4.2.db
1452719 -rw-r--r-- 1 omerda omerda 245760 Jul  7 12:41 /tmp/vf4.db
$
$ mv /tmp/vf4.2.db /tmp/vf4.db
$ ls -li /tmp/*.db
1452722 -rw-r--r-- 1 omerda omerda 245760 Jul  7 12:41 /tmp/vf4.db
Run Code Online (Sandbox Code Playgroud)

这种“往返”总是导致原始 inode 再次附加到原始文件。我本来希望在每个副本中使用一个全新的 inode。

它如何重用相同的 inode?

编辑

在评论部分,有些人要求提供上下文。所以上下文是一些sqlite包装器使用这种不好的做法来替换db文件,而sqlite3没有显示有关替换的错误。但是,这不是关于 sqlite 的问题,请坚持主题和问题。

roa*_*ima 5

系统重用相同的 inode,因为文件系统层选择这样做。正如评论中提到的,这是一个实现细节。在我的情况下,这是ext4,但没有理由为什么不同的文件系统类型不应该以不同的方式使用(或重用)inode。您可能会找到一个没有 inode 的文件系统,并且 inode 编号是根据请求动态合成的。该tmpfs文件系统不会以同样的方式不重用inode编号。

# Create two files on ext4
touch file
cp file copy
ls -li file copy
133235 -rw-r--r-- 1 roaima roaima 0 Jul  7 11:13 copy
129071 -rw-r--r-- 1 roaima roaima 0 Jul  7 11:13 file

# Remove one, copy the other back    
rm file
cp copy file
ls -li file copy
133235 -rw-r--r-- 1 roaima roaima 0 Jul  7 11:13 copy
129071 -rw-r--r-- 1 roaima roaima 0 Jul  7 11:13 file

# Remove one, create an unexpected intervention, copy the other back
rm file
touch thing
cp copy file
ls -li file copy thing
133235 -rw-r--r-- 1 roaima roaima 0 Jul  7 11:13 copy
133237 -rw-r--r-- 1 roaima roaima 0 Jul  7 11:14 file
129071 -rw-r--r-- 1 roaima roaima 0 Jul  7 11:14 thing
Run Code Online (Sandbox Code Playgroud)

现在让我们在tmpfs文件系统上重复,例如/dev/shm

# Create two files on tmpfs
touch file
cp file copy
ls -li file copy
369355 -rw-r--r-- 1 roaima roaima 0 Jul  7 11:27 copy
369354 -rw-r--r-- 1 roaima roaima 0 Jul  7 11:27 file

# Remove one, copy the other back    
rm file
cp copy file
ls -li file copy
369355 -rw-r--r-- 1 roaima roaima 0 Jul  7 11:27 copy
368123 -rw-r--r-- 1 roaima roaima 0 Jul  7 11:28 file
Run Code Online (Sandbox Code Playgroud)

可能有用的参考资料