我有以下情况。
用户可以键入一个进程的PID,脚本应该显示进程,它是PID的subprocess,subprocess(等等),并且应该以树的forms列出。
我尝试使用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, mytest.sh
所示:
$ 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
树限于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
那么,希望这可以帮助别人,
干杯!
这是仅使用ps和awk的bash脚本。 您可以使用at作为生成进程树的基础。
ppid=$1 while true do forloop=FALSE # get all children by pid for i in `ps -ef | awk '$3 == '$ppid' {print $2}'` do # Here you have one of of the elements of tree # parent -> child echo $ppid - $i forloop=TRUE done ppid=$i if [ "$forloop" = "FALSE" ]; then exit fi done
你的第一步是通过awk和grep管道ps。 通过使用awk,可以隔离“此进程PID”字段或“父进程PID”字段。
或者,漫步/ proc文件系统。