![crontab が作業スクリプト経由でサービスを開始できない](https://rvso.com/image/617260/crontab%20%E3%81%8C%E4%BD%9C%E6%A5%AD%E3%82%B9%E3%82%AF%E3%83%AA%E3%83%97%E3%83%88%E7%B5%8C%E7%94%B1%E3%81%A7%E3%82%B5%E3%83%BC%E3%83%93%E3%82%B9%E3%82%92%E9%96%8B%E5%A7%8B%E3%81%A7%E3%81%8D%E3%81%AA%E3%81%84.png)
私のスクリプトは、単独で実行すると動作しますが、crontab 経由では動作しません。
クロンタブ
[root@someserver:/]# crontab -l
SHELL=/bin/bash
PATH=/usr/lib64/qt-3.3/bin:/home/ec2/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
*/1 * * * * /bin/bash /opt/scripts/check_beaver_status.sh
問題のスクリプト
#!/bin/bash
function check_if_beaver_running () {
current_script=`basename $0`
process_name="beaver"
/bin/ps aux | /bin/grep "${process_name}" | /bin/grep -v 'grep' | /bin/grep -v "$current_script"
if [ $? -eq 0 ]; then
echo "${process_name} running"
else
echo "${process_name}: not running, starting..."
if [ -f /var/run/logstash_beaver.pid ] ; then
/bin/rm -f /var/run/logstash_beaver.pid
fi
/sbin/service beaver start
fi
}
check_if_beaver_running
答え1
クロンドは走っていなかった。
[root@someserver:]# service crond status
crond is stopped
[root@someserver:]# service crond start
[root@someserver:]# chkconfig crond on
また、スクリプトを次のように変更しました。
#!/bin/bash
# when running in crontab:
# SHELL=/bin/bash
# PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# */10 * * * * /bin/bash beaver_ensure_running.sh
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
答え2
この答えに非常に興味があるので、診断をお手伝いさせてください。
cron を次のように変更してみてください:
*/1 * * * * /bin/bash -x /opt/scripts/check_beaver_status.sh > /tmp/crondiag.log 2>&1
次のコマンドも追加します:
env
スクリプトの先頭と、スクリプト内の関数呼び出しの末尾の両方に。
一度実行して、結果を私たちと共有してください。おそらく pastie.org か何かで。