プロセスの 1 つが実行されているかどうかを 10 分ごとに確認しようとしています。実行されていない場合は、そのプロセスを再起動します。システムの起動時にこのスクリプトを自動的に開始したいので、 Linux のサービスを探します。
だからここに私がしたことがあります:
- Bash スクリプトをサービスとして作成しました。
- シェルスクリプトの
start
メソッドで、無限 while ループ内で、一時ファイルが存在するかどうかを確認します。利用可能な場合は私のロジックを実行し、そうでない場合はループを中断します。 - メソッドで、
stop
一時ファイルを削除します。 - 次に、update-rc.d を使用して、このスクリプトをシステムの起動時に追加しました。
1 つのことを除いて、すべてが正常に機能していました。実行すると./myservice start
、端末がハングアップします (無限ループを実行しているため) が、実行するctrl-z
とスクリプトが強制終了され、タスクが実行されません。このスクリプトを端末から開始して正常に実行するにはどうすればよいですか? (のように、言う./etc/init.d/mysql start
)。バックグラウンドでプロセスを実行して戻る場合があります。
私の Bash スクリプトを以下に示します。
#!/bin/bash
# Start the service
start() {
#Process name that need to be monitored
process_name="mysqld"
#Restart command for process
restart_process_command="service mysql start"
#path to pgrep command
PGREP="/usr/bin/pgrep"
#Initially, on startup do create a testfile to indicate that the process
#need to be monitored. If you dont want the process to be monitored, then
#delete this file or stop this service
touch /tmp/testfile
while true;
do
if [ ! -f /tmp/testfile ]; then
break
fi
$PGREP ${process_name}
if [ $? -ne 0 ] # if <process> not running
then
# restart <process>
$restart_process_command
fi
#Change the time for monitoring process here (in secs)
sleep 1000
done
}
stop() {
echo "Stopping the service"
rm -rf /tmp/testfile
}
### main logic ###
case "$1" in
start)
start
;;
stop)
stop
;;
status)
;;
restart|reload|condrestart)
stop
start
;;
*)
echo $"Usage: $0 {start|stop|restart|reload|status}"
exit 1
esac
exit 0