获取从 parent 个进程创建的所有 child/grandchild 个进程的 pids

Get pids of all child/grandchild processes created from parent process

假设我有这样一个过程:

#!/usr/bin/env bash

node foo.js &
pid=$!

有没有办法监听从 pid 创建的 child 进程? 我想创建一个从 pid 获取 created/forked 的 pid 列表。即pid的任何child或grandchild,我想了解一下,somehow.

是的,现在我将每个 child 进程的 pid 记录到 stdout 并以这种方式捕获它,但是这有几个问题。这不是一个通用的解决方案,特别是如果我不控制所有 child 过程,或者如果它们的标准输出被重定向。

您可以通过 pstree 或 ps --tree.

获取子进程 pid

我认为解决这个问题的最佳方法是使用这种方法:

#!/usr/bin/env bash

node foo.js &
pid=$!

sleep 5;

pgrep -P $pid | xargs kill -INT

这将向 $pid 的所有子进程发送 SIGINT 信号。

https://linux.die.net/man/1/pgrep