pgrep defunct进程重启服务

时间:2013-09-17 17:00:24

标签: linux bash unix process cron

My Current cronjob如果没有运行将启动beaver:

#!/bin/bash
pgrep -l -x beaver || /usr/sbin/service beaver start

我想修改它以便在海狸失效时采取行动(通过重新启动海狸服务,如果失败则杀死它(pkill -u beaver)

# ps -ef | grep [b]eaver
beaver    2890     1  0 Sep15 ?        00:11:27 /usr/bin/python /usr/local/bin/beaver -t sqs -c /etc/beaver/beaver.conf
beaver    2899  2890  0 Sep15 ?        00:03:01 [beaver] <defunct>
# pgrep -l -x beaver
2890 beaver
2899 beaver

建议?

1 个答案:

答案 0 :(得分:1)

你可以尝试这个:

#!/bin/bash
START=false
readarray -t PIDS < <(exec pgrep -x beaver)

function stop_beaver {
    /usr/sbin/service beaver stop
    sleep 5s  ## Optionally wait for processes to stop.
    kill -s SIGTERM "${PIDS[@]}" ## Perhaps force another signal to them if it doesn't work with defuncts.
    sleep 5s  ## Optionally wait for processes to stop.
    kill -s SIGKILL "${PIDS[@]}" ## Perhaps force another signal to them if it doesn't work with defuncts.
    START=true
}
if [[ ${#PIDS[@]} -eq 0 ]]; then
    echo "No beaver process was found."
    START=true
elif [[ ${#PIDS[@]} -eq 1 ]]; then
    echo "Processes found: ${PIDS[*]}"
    echo "Only one beaver process found."
    stop_beaver
elif ps -fp "${PIDS[@]}" | fgrep -F '<defunct>' >/dev/null; then
    echo "Processes found: ${PIDS[*]}"
    echo "Defunct beaver process found."
    stop_beaver
else
    echo "Processes found: ${PIDS[*]}"
fi
[[ $START == true ]] && /usr/sbin/service beaver start