栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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']
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/870188.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号