Shell 腳本程序往往會創建很多進程,當出現問題或者想終止執行的時候很麻煩,有時候忘記kill子進程,會出現一些很詭異的情況(如子進程需要寫文件)。寫個腳本kill進程樹,方便以後系統維護使用。
- #!/bin/sh
-
- if [ $# -ne 1 ]
- then
- echo -e "\033[;36mUsage:\033[0m" "\033[;32mkillall\033[0m" "\033[;33mPID\033[0m"
- exit
- else
- root=$1
- fi
-
- function treekill()
- {
- local father=$1
-
- # children
- childs=(`ps -ef | \
- awk -v father=$father 'BEGIN{ ORS=" "; } $3==father{ print $2; }'`)
- if [ ${#childs[@]} -ne 0 ]
- then
- for child in ${childs[*]}
- do
- treekill $child
- done
- fi
-
- # father
- echo -e "\033[;32mkill\033[0m" "\033[;36mpid\033[0m" "\033[;33m$father\033[0m"
- kill -9 $father
- }
-
- treekill $root
測試一下:
test.sh 如下
- #!/bin/sh
-
- sh ./test1.sh &
- sleep 55555555 &
- sleep 7777777
test1.sh 如下
- #!/bin/sh
-
- sleep 55555555 &
- sleep 7777777
運行
- sh test.sh &
- killtree pid # test.sh 的進程ID