美文网首页
杀死进程树

杀死进程树

作者: millerix | 来源:发表于2018-06-20 10:35 被阅读0次
    function getchld_kill()
    {
            if [[ -z "$1" ]];
            then
                    echo "arguemnt 1 should be a number";
                    exit;
            fi
            local child
            local father=$1
    #        echo  "father: ${father}"
            local childs=$(ps -ef | awk -v father=$father 'BEGIN{ ORS=" "; } $3==father{ print $2; }')
    #        echo "childs: " ${childs[*]}
            if [[ ${#childs[@]} -ne 0 && -n "${childs[0]}" ]];
            then
                    for child in ${childs[@]}
                    do
    #                       echo child:${child}
                            getchld_kill ${child}
                    done
                    echo "killing the father: ${father}"
                    kill -9 ${father}
            else
                    echo "killing myself pid:${father}"
                    kill -9 ${father}
                    return
            fi
    }
    
    getchld_kill $1
    

    使用递归调用实现了树的深度优先遍历:
    递归条件是 childs 数组不空, 且第一个元素非空( awk 在叶子上返回一个第一个元素是空的数组)
    base line condition 设置在叶子进程上进行递归返回.
    getchld_kill 的参数是树根进程.

    相关文章

      网友评论

          本文标题:杀死进程树

          本文链接:https://www.haomeiwen.com/subject/srmtyftx.html