如果知道进程打开的文件的文件描述符,如何在 linux 命令上打印文件名?

tec*_*fun 5 linux command-line linux-mint lsof

我知道进程打开的文件的文件描述符,但我不知道进程 ID。如果我知道进程打开的文件的文件描述符,如何从 Linux 命令提示符打印文件名?

use*_*686 5

如果您不知道进程 ID,则必须检查所有打开相同 fd# 的进程,因为文件描述符不是全局唯一的。fd# 越小,打开它的进程就越多(例如,在我的系统上,即使 fd# 大约为 30,我仍然需要在 15 个进程之间进行猜测,如果我正在寻找 10 左右的 fd#,那么该列表将有大约 170 个进程)。

proc 文件系统将文件描述符显示为./proc/<pid>/fd

# ls -l /proc/1/fd
lrwx------ 1 root root 64 Feb 12 22:10 /proc/1/fd/0 -> /dev/null
lrwx------ 1 root root 64 Feb 12 22:10 /proc/1/fd/1 -> /dev/null
lrwx------ 1 root root 64 Feb 12 22:10 /proc/1/fd/2 -> /dev/null
l-wx------ 1 root root 64 Feb 12 22:10 /proc/1/fd/3 -> /dev/kmsg
lrwx------ 1 root root 64 Feb 12 22:10 /proc/1/fd/4 -> anon_inode:[eventpoll]
lrwx------ 1 root root 64 Feb 12 22:10 /proc/1/fd/5 -> anon_inode:[signalfd]
lr-x------ 1 root root 64 Feb 12 22:10 /proc/1/fd/6 -> /sys/fs/cgroup/systemd/
...等等...

例如,要在所有进程中查找 fd #5:

# ls -l /proc/*/fd/5
lrwx------ 1 root root 64 Feb 12 22:10 /proc/1/fd/5 -> anon_inode:[signalfd]
lrwx------ 1 root root 64 Feb 12 22:15 /proc/129/fd/5 -> socket:[6980]
lrwx------ 1 root root 64 Feb 12 22:15 /proc/168/fd/5 -> socket:[7847]
lrwx------ 1 root root 64 Feb 12 22:15 /proc/341/fd/5 -> anon_inode:[eventfd]
lr-x------ 1 root root 64 Feb 12 22:15 /proc/342/fd/5 -> anon_inode:inotify
...等等...

解析符号链接目标的确切接口是readlink()

# 读取链接 /proc/427529/fd/7
/home/grawity/lib/dotfiles/vim/backup/%home%grawity%.bashrc.swp