在Python 3中查找给定套接字和inode的进程ID

5ba*_*be2 3 sockets linux procfs python-3.x python-3.2

/ proc/net/tcp给我一个套接字的本地地址,端口和inode号(例如0.0.0.0:5432和9289).

鉴于上述信息,我想找到特定过程的PID.

可以打开/ proc中的每个编号文件夹,然后使用shell命令检查符号链接以查找套接字/ inode编号,例如"$ sudo ls -l/proc/*/fd/2>/dev/null | grep socket".但是,这似乎比必要的计算成本更高,因为任何给定系统上<5%的进程都有开放的TCP套接字.

查找已打开给定套接字的PID的最有效方法是什么?我更喜欢使用标准库,而我目前正在使用Python 3.2.3进行开发.

编辑:从问题中删除了代码示例,因为它们现在包含在下面的答案中.

5ba*_*be2 5

以下代码实现了原始目标:

def find_pid(inode):

    # get a list of all files and directories in /proc
    procFiles = os.listdir("/proc/")

    # remove the pid of the current python process
    procFiles.remove(str(os.getpid()))

    # set up a list object to store valid pids
    pids = []

    for f in procFiles:
        try:
            # convert the filename to an integer and back, saving the result to a list
            integer = int(f)
            pids.append(str(integer))
        except ValueError:
            # if the filename doesn't convert to an integer, it's not a pid, and we don't care about it
            pass

    for pid in pids:
        # check the fd directory for socket information
        fds = os.listdir("/proc/%s/fd/" % pid)
        for fd in fds:
            # save the pid for sockets matching our inode
            if ('socket:[%d]' % inode) == os.readlink("/proc/%s/fd/%s" % (pid, fd)):
                return pid
Run Code Online (Sandbox Code Playgroud)