pgrep -P, but for grandchildren not just children

前端 未结 6 2243
猫巷女王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:58

    The code below will print the PIDs of the current process and all its descendants. It uses a Bash array as a queue to implement a breadth-first search of the process tree.

    unprocessed_pids=( $$ )
    while (( ${#unprocessed_pids[@]} > 0 )) ; do
        pid=${unprocessed_pids[0]}                      # Get first elem.
        echo "$pid"
        unprocessed_pids=( "${unprocessed_pids[@]:1}" ) # Remove first elem.
        unprocessed_pids+=( $(pgrep -P $pid) )          # Add child pids
    done
    

提交回复
热议问题