pgrep -P, but for grandchildren not just children

前端 未结 6 2222
猫巷女王i
猫巷女王i 2021-01-07 05:18

I am using:

pgrep -P $$

to get the child pids of $$. But I actually want a list of grandchildren and great grandchild too.

How do I

6条回答
  •  耶瑟儿~
    2021-01-07 05:51

    If pgrep doesn't do what you want, you can always use ps directly. Options will be somewhat platform-dependent.

    ps -o ppid,pid |
    awk -v pid=$$ 'BEGIN { parent[pid] = 1 }  # collect interesting parents
        { child[$2] = $1 }  # collect parents of all processes
        $1 == pid { parent[$2] = 1 }
        END { for (p in child)
            if (parent[child[p]])
              print p }'
    

    The variable names are not orthogonal -- parent collects the processes which are pid or one of its children as keys, i.e. the "interesting" parents, and child contains the parent of each process, with the process as the key and the parent as the value.

提交回复
热议问题