You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取指定进程的孙子及曾孙进程PID?适合新手的简单方案

新手友好的进程后代查询实现方案

核心逻辑非常简单:你已经知道可以查询指定PID的直接子进程,只要把每轮查到的子进程作为新的父PID,重复查询就能拿到所有层级的后代,不需要复杂的管道或过滤逻辑。

方案1:基于你已掌握的pgrep实现

如果你可以用pgrep,直接用最易懂的循环遍历每一层即可:

# 替换为你要查询的根PID
root_pid=1234
# 初始化当前需要查询的父PID列表
current_parent_pids="$root_pid"

# 循环查询直到没有新的后代进程
while [ -n "$current_parent_pids" ]; do
    next_parent_pids=""
    for pid in $current_parent_pids; do
        # 查询当前PID的直接子进程
        child_pids=$(pgrep -P $pid)
        if [ -n "$child_pids" ]; then
            # 输出查到的后代PID,可按需修改为写入文件/存入变量
            echo $child_pids
            next_parent_pids="$next_parent_pids $child_pids"
        fi
    done
    # 更新下一轮要查询的父PID列表
    current_parent_pids=$next_parent_pids
done

每轮循环对应查询一层后代:第一轮拿到的是子进程(儿子辈),第二轮是孙子辈,第三轮是曾孙辈,以此类推。

方案2:纯ps -P实现(不依赖pgrep,符合补充要求)

ps -P和pgrep -P的查询逻辑完全一致,只要指定输出格式过滤出纯PID即可,替换方案1中的pgrep -P即可:

root_pid=1234
current_parent_pids="$root_pid"

while [ -n "$current_parent_pids" ]; do
    next_parent_pids=""
    for pid in $current_parent_pids; do
        # -o pid= 表示只输出PID列,去掉表头,输出结果和pgrep -P完全一致
        child_pids=$(ps -P $pid -o pid=)
        if [ -n "$child_pids" ]; then
            echo $child_pids
            next_parent_pids="$next_parent_pids $child_pids"
        fi
    done
    current_parent_pids=$next_parent_pids
done

极简限定层级版本(仅查孙子+曾孙)

如果你不需要查所有后代,只要孙子和曾孙,连循环都可以省,直接写固定层级的查询逻辑,完全没有理解门槛:

root_pid=1234
# 1. 查询儿子辈PID
child_pids=$(ps -P $root_pid -o pid=)
# 2. 查询孙子辈PID
grandchild_pids=$(for p in $child_pids; do ps -P $p -o pid=; done)
echo "孙子辈PID:$grandchild_pids"
# 3. 查询曾孙辈PID
great_grandchild_pids=$(for p in $grandchild_pids; do ps -P $p -o pid=; done)
echo "曾孙辈PID:$great_grandchild_pids"

内容的提问来源于stack exchange,提问作者Nathace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 12:21:03