【问题标题】:How to reimplement lsof +D on MacOS two avoid calling stat(2) twice?如何在 MacOS 上重新实现 lsof +D 两次避免调用 stat(2) 两次?
【发布时间】:2022-11-10 06:15:07
【问题描述】:

我正在使用lsof 来检测给定目录的哪个进程打开了哪些文件。例子:

% lsof +D /Users/jack/Downloads
Spotify 1431 jack   75r   DIR    1,6      128 37333 /Users/jack/Downloads/file1.png
Dock    1439 jack   13r   DIR    1,6      128 37333 /Users/jack/Downloads/foo.psd
zsh     6644 jack  cwd    DIR    1,6      128 37333 /Users/jack/Downloads/foo.bmp

lsof(8) 的手册页指出:

lsof 可能会缓慢处理此选项并需要 大量的动态内存来做。这是因为它必须 下降整个目录树,以 D 为根,调用 stat(2) 为 每个文件和目录,构建它找到的所有文件的列表, 并在该列表中搜索与每个打开文件的匹配项。什么时候 D目录很大,这些步骤可能需要很长时间,所以使用这个 谨慎选择。

巧合的是,在我调用lsof 之前,我已经在遍历目录并在Python 中调用os.stat,这意味着stat(2) 在技术上被调用了两次。

stat 对象包含哪些信息可以让我自己处理以模仿lsof 的功能?非常感谢任何帮助!

【问题讨论】:

  • 你能展示你的 python 程序在做什么,为什么以及如何调用 lsof ?

标签: python macos file-descriptor lsof


【解决方案1】:

您可以使用/proc 文件系统轻松地按进程查找打开的文件。来自manpage:

/proc/[pid]/fd/ This is a subdirectory containing one entry for each file which the process has open, named by its file descriptor, and which is a symbolic link to the actual file. Thus, 0 is standard input, 1 standard output, 2 standard error, and so on. For file descriptors for pipes and sockets, the entries will be symbolic links whose content is the file type with the inode. A readlink(2) call on this file returns a string in the format: type:[inode]

这是一个小示例脚本,列出了每个进程的所有打开文件。

import os

def find_open_files(pid, prefix="/"):
    fds = os.listdir(f"/proc/{pid}/fd")
    open_files = []
    for fd in fds:
        try:
            # read the symlink from the file descrptior files
            open_file = os.readlink(f"/proc/{pid}/fd/{fd}")
            # this is a simple filter to only show "real" files
            # as stated in the manpage open_file could be something like socket:[1234]
            if open_file.startswith(prefix):
                open_files.append(open_file)
        except FileNotFoundError:
            # These errors happen, if
            #  1. the process exits in the time between our listdir and the readlink
            #  2. the file is closed before we reach readlink
            pass
    return open_files


proc_files = os.listdir("/proc")
# find all numeric dirs as there are also other dirs in /proc present
pids = [p for p in proc_files if p.isnumeric()]
all_open_files = {}
for pid in pids:
    all_open_files[pid] = find_open_files(pid)

print(all_open_files)

【讨论】:

    猜你喜欢
    • 2021-12-14
    • 2011-01-11
    • 1970-01-01
    • 2021-05-16
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多