[Python] [Linux] 统计进程组中所有的进程号

[Python] [Linux] 统计进程组中所有的进程号,第1张

linux中进程呈现树状结构,一个进程可能有若干个子进程,最多有一个父进程。在文件/proc/$pid/task/$pid/children中存放了该进程的子进程号,用空格分隔。

ljq@ljq1:/home/fujx/controller$ cat /proc/1/task/1/children 
313 337 352 750 906 920 928 1011 1015 1018 1025 1078 1226 1274 1360 1432 1489 1523 1935 2032 2034 2075 2430 2554 2581 3021 3071 13972 13976

该文件不能直接访问到子进程的子进程,但是由于知道了子进程的pid,因此可以再访问子进程对应的children文件,找到孙进程,递归找到所有的后代进程。

使用深度优先搜索和广度优先搜索的方式都能达到目的,下面展示深度优先的代码

def collectPids(pid):
    pid_list = []
    try:
        with open("/proc/" + str(pid) + "/task/" + str(pid) + "/children") as f:
            pid_list.append(pid)
            line = f.readline()
            pids = line.split(' ')
            for ppid in pids:
                pid_list = pid_list + collectPids(ppid)

    except:
        pass

    return pid_list

if __name__ == '__main__':
    ipt = input()
    lists = collectPids(ipt)
    print(lists)
(base) root@ljq1:/home/fujx/controller# python testPid.py 
2
['2', '4', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '18', '19', '20', '21', '22', '24', '25', '26', '27', '28', '30', '31', '32', '33', '34', '36', '37', '38', '39', '40', '42', '43', '44', '45', '46', '48', '49', '50', '51', '52', '54', '55', '56', '57', '58', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '83', '84', '85', '127', '128', '129', '130', '131', '132', '138', '147', '164', '165', '167', '230', '232', '233', '235', '243', '248', '261', '275', '276', '278', '545', '547', '561', '4389', '8289', '12225', '12336', '12576', '13257', '13268', '13579', '13744', '13986', '14608', '19360', '19391', '19542', '29069', '896', '903', '1514', '2127', '2252']

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/883900.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-14
下一篇 2022-05-14

发表评论

登录后才能评论

评论列表(0条)

保存