我有以下场景。
用户将键入进程的 PID,脚本应显示进程及其 PID 的子进程、子进程(等等),并应以树格式列出。
我尝试使用 pstree PID
和 ps faux PID
,但它不起作用。似乎它没有将进程的 PID 作为参数。
有什么想法吗?
最佳答案
只是想记录我与此问题相关的步骤。
假设我在终端中执行:
~$ echo "read -p 'Press Enter'" > mytest.sh
~$ chmod +x mytest.sh
~$ bash -c bash
~$ bash -c ./mytest.sh
... 并让它在 read
输入提示处等待。然后,我总能找到 mytest.sh
的 pid,例如:
$ ps axf | grep mytest
20473 pts/2 S+ 0:00 | | \_ grep --color=tty mytest
20308 pts/5 S+ 0:00 | | \_ bash -c ./mytest.sh
...但是,我想输出一个 ps axf
树,限制为 mytest.sh
的某个父级;查看完整的 ps axf
,我们可以看到一个层次结构:
$ ps axf
1489 ? Sl 1:39 \_ gnome-terminal --sm-client-id 106ab86
1511 ? S 0:00 | \_ gnome-pty-helper
...
20238 pts/5 Ss 0:00 | \_ bash
20274 pts/5 S 0:00 | | \_ bash
20308 pts/5 S+ 0:00 | | \_ bash -c ./mytest.sh
...
然后,假设我不想作为父级“扫描”gnome-terminal
(1489),而是想从 bash
(20238) 开始.. 所以,我想获得这个输出:
$ ps f -p 20238 20274 20308
PID TTY STAT TIME COMMAND
20238 pts/5 Ss 0:00 bash
20274 pts/5 S 0:00 \_ bash
20308 pts/5 S+ 0:00 \_ bash -c ./mytest.sh
...除了,我不想手动复制/粘贴子 PID :)
我可以使用pstree
:
$ pstree -a -p 20238
bash,20238
└─bash,20274
└─bash,20308 -c ./mytest.sh
$ pstree -p 20238
bash(20238)───bash(20274)───bash(20308)
...不幸的是,输出与我更喜欢的 ps axf
中的输出不完全相同。
所以,我可以简单地使用 pstree
来获取子 PID:
$ pstree -p 20238 | sed 's/(/\n(/g' | grep '(' | sed 's/(\(.*\)).*/\1/'
20238
20274
20308
$ pstree -p 20238 | sed 's/(/\n(/g' | grep '(' | sed 's/(\(.*\)).*/\1/' | tr "\n" ,
20238,20274,20308,
然后使用它们来获取 ps axf
树,仅基于父级的 PID:
$ ps f -p $(pstree -p 20238 | sed 's/(/\n(/g' | grep '(' | sed 's/(\(.*\)).*/\1/' | tr "\n" " ")
PID TTY STAT TIME COMMAND
20238 pts/5 Ss 0:00 bash
20274 pts/5 S 0:00 \_ bash
20308 pts/5 S+ 0:00 \_ bash -c ./mytest.sh
好吧,希望这对某人有帮助,
干杯!
关于linux - 遍历进程树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5213973/