sda*_*aau 26
只想记录与此问题相关的步骤.
假设我在终端中执行此操作:
~$ echo "read -p 'Press Enter'" > mytest.sh
~$ chmod +x mytest.sh
~$ bash -c bash
~$ bash -c ./mytest.sh
Run Code Online (Sandbox Code Playgroud)
...并在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
Run Code Online (Sandbox Code Playgroud)
...但是,我想输出一个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
...
Run Code Online (Sandbox Code Playgroud)
然后,说我不想' 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
Run Code Online (Sandbox Code Playgroud)
...除外,我不想手动复制/粘贴子PID :)
我可以用pstree
:
$ pstree -a -p 20238
bash,20238
??bash,20274
??bash,20308 -c ./mytest.sh
$ pstree -p 20238
bash(20238)???bash(20274)???bash(20308)
Run Code Online (Sandbox Code Playgroud)
...不幸的是,输出与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,
Run Code Online (Sandbox Code Playgroud)
然后使用它们来获取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
Run Code Online (Sandbox Code Playgroud)
嗯,希望这有助于某人,
干杯!
第一步是通过 awk 和 grep 通过管道传输 ps。通过使用 awk,您可以隔离“此进程 PID”字段或“父进程 PID”字段。
或者,浏览一下 /proc 文件系统。