如何识别两个文件脚本是否指向同一个文件

How to identify if two file diescriptors point to the same file

我正在编写一个必须处理文件的程序 (open/write/close/etc)。如果我打开一个文件并获得一个文件描述符,而其他一些进程将该文件移动到文件系统上的另一个位置,我之前获得的文件描述符仍然有效。例如:

SYS_exit equ 0x3C
SYS_inotify_init equ 253
SYS_read equ 0x00
SYS_open equ 0x02
O_RDONLY equ 0x00
O_WRONLY equ 0x01
O_RDWR equ 0x02

section .text
    global _start

_start:
    mov rax, SYS_inotify_init
    syscall
    mov r13, rax            ;storing inotify instance

    mov rax, SYS_open
    mov rdi, dir_name_moved_from_file
    mov rsi, O_RDWR
    mov rdx, 0x00
    syscall                 ; <---- OPEN 1

    mov rax, SYS_open
    mov rdi, dir_name_moved_from_file
    mov rsi, O_RDWR
    mov rdx, 0x00
    syscall                 ; <---- OPEN 2

    ;listening inotify events and doing some other useful things

    mov eax, SYS_exit
    mov rdi, 0x00
    syscall

section .data
    dir_name_moved_from_file: db '/tmp/data/test', 0

问题是 OPEN 1OPEN 2 返回的文件描述符不同,即使我打开同一个文件两次。

问题:是否有独立于文件系统的方法来识别文件是否已被当前进程打开?

fstat 在 FD 上,比较 ​​st_devst_ino。如果它们相等,则您有相同的文件。对于同一个 inode,可能已经使用不同的硬链接名称打开了 FD,但这种情况被认为是对同一个文件有多个名称。

fstat 正是 GNU cmp 所做的,如果你 strace 就可以看到。 (如果你给它两次相同的输入,它有一个提前退出检查。)

But why is it true only for the same filesystems? As I checked inode number contains the location on a harddrive which seems to me filesystem independent

每个 st_dev 都有自己的 st_ino 地址 space。 inode 编号对应于文件系统 中的位置,而不是相对于物理硬盘驱动器的起始位置。所以通常它是相对于 FS 分区的开始。

其他任何方式都没有意义:文件系统不关心它们是在 RAID 上,还是由具有 Linux LVM 的多个硬盘驱动器的部分组成的逻辑块设备,或者随便。