脚本将PID作为参数,并打印所有子孙、孙子、孙女等的PID。

问题描述 投票:1回答:1

我是编程新手。我知道的是每个进程都可以创建一个子进程。当你打开一个终端时,一个进程被创建,当你在终端中调用一个命令时,一个子进程被创建。我想看看这个子进程,了解它的工作原理。我的朋友和我分享了他的代码,但是对我来说太复杂了。我想把它变得更简单。我希望有人能帮助我。祝大家有一个美好的一天! 下面是代码。

    #!/bin/bash

#Function that will display the process with the parent process ID given as argument
function get_child()
{
        #depth will hold the number of generation. E.g 0 for main process, 1 for children, 2 for grandchildre and so on

local depth=$depth
        # ps --ppid $parent will get the processes whose parent ID is $parent

output=`ps --ppid $parent`
        #increment the depth

depth=$(($depth+1))
        # Pipe the value of $output to tail -n + 2. It will remove the first line from $output because that line only contains title of the columns
        # awk '{print $1}' will only print the first column (Process ID) of eachline
        # While read child will iterate over all the process IDs referred as $child

echo "$output" | tail -n +2 | awk '{print $1}' | while read child

do
                #If $child is not empty i.e. it contains a process ID then echo the child process id and send that process id as parent process id to the get_child() function recursively

if [ $child ]
                then
                        for((i=0;i<depth;i++))
                        do
                                echo -n "-"
                        done
                        echo $depth. $child
                        parent=$child
                        get_child $child $depth
                fi
        done
}

parent=$1
depth=0
echo $parent
get_child $parent $depth
linux bash shell linux-device-driver
1个回答
2
投票

你的算法的简版。

我故意不做评论,你可以自己去研究一下Bash的特性和语法,自己积累一些知识,为你的作业做准备。

#!/usr/bin/env bash

get_child()
{
  local -i pid=0 ppid=$1 depth=$2
  printf '%*s%d. %d\n' "$depth" '' "$depth" "$ppid"
  while read -r pid; do
    ((pid)) && get_child $pid $((depth + 1))
  done < <(ps -o pid= --ppid $ppid)
}

get_child $1 0

没有Bash主义的版本。

#!/usr/bin/env sh

get_child()
{
  p=0
  printf '%*s%d. %d\n' $2 '' $2 $1
  ps -o pid= --ppid $1 |
    while read -r p; do
      [ $p -ne 0 ] && get_child $p $(($2 + 1))
    done
}

get_child $1 0
© www.soinside.com 2019 - 2024. All rights reserved.