デーモンのように起動および停止できるように、シェルスクリプトのサービスをどのように生成できますか?

デーモンのように起動および停止できるように、シェルスクリプトのサービスをどのように生成できますか?

私はCentOS 7を使用しており、私の目標は5秒ごとにcronを作成することです。しかし、私が調査したところによると、cronは1分間しか使用できないので、今やりたいことはシェルファイルを作成することです。
打つ

while sleep 5; do curl http://localhost/test.php; done

しかし、右クリックして手動でクリックしました。

私が望むのは、このファイルのサービスを作成して自動的に起動および停止できるようにすることです。

見つけました。サービス生成スクリプト

#!/bin/bash
# chkconfig: 2345 20 80
# description: Description comes here....

# Source function library.
. /etc/init.d/functions

start() {
    # code to start app comes here 
    # example: daemon program_name &
}

stop() {
    # code to stop app comes here 
    # example: killproc program_name
}

case "$1" in 
    start)
       start
       ;;
    stop)
       stop
       ;;
    restart)
       stop
       start
       ;;
    status)
       # code to check status of app comes here 
       # example: status program_name
       ;;
    *)
       echo "Usage: $0 {start|stop|status|restart}"
esac

exit 0 

ところで、startメソッドやstopメソッドに何を書くべきかわからないので、hit.shのような内容を入れてみましたが、start(){}stopメソッドでエラーが発生しました。}

ベストアンサー1

最新のシステムでスクリプトをデーモンとして実行するユーザーは、次のものを使用する必要がありますsystemd

[Unit]
Description=hit service
After=network-online.target

[Service]
ExecStart=/path/to/hit.sh

[Install]
WantedBy=multi-user.target

別の名前で保存してから、などを/etc/systemd/system/hit.service使用して起動/停止/有効化/無効化することができます。systemctl start hit

2015年の古い回答:

コード例を再利用するには、次のようにします。

#!/bin/bash

case "$1" in 
start)
   /path/to/hit.sh &
   echo $!>/var/run/hit.pid
   ;;
stop)
   kill `cat /var/run/hit.pid`
   rm /var/run/hit.pid
   ;;
restart)
   $0 stop
   $0 start
   ;;
status)
   if [ -e /var/run/hit.pid ]; then
      echo hit.sh is running, pid=`cat /var/run/hit.pid`
   else
      echo hit.sh is NOT running
      exit 1
   fi
   ;;
*)
   echo "Usage: $0 {start|stop|status|restart}"
esac

exit 0 

もちろん、サービスとして実行したいスクリプトはに移動する必要があり/usr/local/bin/hit.sh、上記のコードはに移動する必要があります/etc/init.d/hitservice

このサービスを実行する必要がある各ランレベルに対応するシンボリックリンクを作成する必要があります。たとえば、シンボリックリンクという名前は/etc/init.d/rc5.d/S99hitserviceランレベル5サービスを開始します。もちろん、service hitservice start/を介して手動で開始および停止することもできます。service hitservice stop

おすすめ記事