linux - 以 PID 作为操作数并打印其所有子代、孙代等的 PID 的脚本

标签 linux bash shell

我是编程新手。据我所知,每个进程都可以创建一个子进程。当你打开一个终端时,一个进程被创建,当你在终端内调用一个命令时,一个子进程被创建。我想看看那个子进程并了解它是如何工作的。我的 friend 与我分享了他的代码,但对我来说太复杂了。我想让它更简单。我希望有一个人可以帮助我。祝大家有个愉快的一天!这是代码:

    #!/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

最佳答案

您的算法的简短版本。

我特意不加评论,这样你就可以研究 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

无 Bashism 版本:

#!/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

关于linux - 以 PID 作为操作数并打印其所有子代、孙代等的 PID 的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62119806/

相关文章:

c - 如何在 Arduino 软件 (1.6.5) 中#include <termios.h>?

c++ - Linux MinGW : on compiling he output list of 8 "nultiple definitions"

linux - 在 linux 中添加到 $PATH 以便守护进程可用

python - Linux 和 python : Combining multiple wave files to one wave file

linux - 在远程服务器上执行两个命令并使用 shell 脚本将输出存储到本地服务器

Bash - 如何检索 'or' 语句中第一个命令的退出状态

bash - d=${c//[^$b]} 如何统计字母$b在$c中出现了多少次?

linux - 如何在 linux 中的 tcsh shell 上执行此操作

shell - 从 CURL 保存的 cookie 文件中读取 session ID

linux - 如何修复 bash 脚本中意外的文件结尾?