抱歉,评论被关闭
Shell如何创建进程树?
进入字符页面的 linux 进程的管理,如果需要用进程来强制关闭部分程序,那进程树的管理是必须掌握的!
下面是shell创建进程树的代码(此代码的作者ron peters):
#!/bin/bash
#
# Display process table in tree form
#
if [ "$1" = "" ]
then
proc=1
else
proc=$1
fi
main () {
PSOUT=`ps -ef | grep -v "^UID" | sort -n -k2`
# This technique will work in ksh, but since there are going to be array
# subscripts larger than 1024, bash is the way to go.
#ps -ef | grep -v "^UID" | while read line
while read line
do
line=`echo "$line" | sed -e s/\>/\\\\\\>/g`
#echo $line
# works in ksh/pdksh as long as the subscript is below 1024.. here it is not
# bash works fine though.
#set -A process $line for a ksh script
declare -a process=( $line )
pid=${process[1]}
owner[$pid]=${process[0]}
ppid[$pid]=${process[2]}
command[$pid]="`echo $line | awk '{for(i=8;i<=NF;i++) {printf "%s ",$i}}'`"
#此处算法,通过的父pid来定位,巧用 good!
children[${ppid[$pid]}]="${children[${ppid[$pid]}]} $pid"
done <<EOF
$PSOUT
EOF
# something about the arrays is that the values seem to be only good in the
# above loop. This is a known issue with bash that all the piped elements
# are in subshells and their variables aren't available to the parent shell.
# Take the pipe out of the equation and send it to a file, then redirect
# the file into the end of the while loop.
print_tree $proc ""
}
print_tree () {
id=$1
echo "$2$id" ${owner[$id]} ${command[$id]}
if [ "${children[$id]}" = "" ]
then
return
else
for child in ${children[$id]}
do
if [ "$child" = "`echo ${children[${ppid[$child]}]} | awk '{print $NF}'`" ]
then
echo "$2 \\"
temp="$2 "
else
echo "$2|\\"
temp="$2| "
fi
print_tree $child "$temp"
done
fi
}
main
运行结果(部分树结构 可传入指定ID打印该进程树):
1 root init [5] |\ | 2 root [migration/0] |\ | 3 root [ksoftirqd/0] |\ | 4 root [watchdog/0] |\ | 5 root [migration/1] |\ | 6 root [ksoftirqd/1] |\ | 7 root [watchdog/1] |\ | 8 root [migration/2] |\ | 9 root [ksoftirqd/2] |\ | 10 root [watchdog/2] |\ | 11 root [migration/3]
本文出自 “凹凸曼” 博客,请务必保留此出处 http://www.apoyl.com/?p=1118
日志信息 »
该日志于2011-08-10 14:46由 凹凸曼 发表在Shell分类下,
评论已关闭。
目前盖楼

