Finding a process ID given a socket and inode in Python 3

前端 未结 2 900
既然无缘
既然无缘 2021-01-03 08:55

/proc/net/tcp gives me a local address, port, and inode number for a socket (0.0.0.0:5432 and 9289, for example).

I\'d like to find the PID for a specific process, g

2条回答
  •  梦毁少年i
    2021-01-03 09:19

    The following code accomplishes the original goal:

    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
    

提交回复
热议问题