歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Shell Kill 進程樹

Shell Kill 進程樹

日期:2017/3/1 10:22:54   编辑:SHELL編程

Shell 腳本程序往往會創建很多進程,當出現問題或者想終止執行的時候很麻煩,有時候忘記kill子進程,會出現一些很詭異的情況(如子進程需要寫文件)。寫個腳本kill進程樹,方便以後系統維護使用。

  1. #!/bin/sh
  2. if [ $# -ne 1 ]
  3. then
  4. echo -e "\033[;36mUsage:\033[0m" "\033[;32mkillall\033[0m" "\033[;33mPID\033[0m"
  5. exit
  6. else
  7. root=$1
  8. fi
  9. function treekill()
  10. {
  11. local father=$1
  12. # children
  13. childs=(`ps -ef | \
  14. awk -v father=$father 'BEGIN{ ORS=" "; } $3==father{ print $2; }'`)
  15. if [ ${#childs[@]} -ne 0 ]
  16. then
  17. for child in ${childs[*]}
  18. do
  19. treekill $child
  20. done
  21. fi
  22. # father
  23. echo -e "\033[;32mkill\033[0m" "\033[;36mpid\033[0m" "\033[;33m$father\033[0m"
  24. kill -9 $father
  25. }
  26. treekill $root

測試一下:

test.sh 如下

  1. #!/bin/sh
  2. sh ./test1.sh &
  3. sleep 55555555 &
  4. sleep 7777777
test1.sh 如下
  1. #!/bin/sh
  2. sleep 55555555 &
  3. sleep 7777777
運行
  1. sh test.sh &
  2. killtree pid # test.sh 的進程ID
Copyright © Linux教程網 All Rights Reserved