systemd 機能は、以前のリリースの古い System-V 初期化スクリプトを置き換えます。 systemd は、非依存サブシステムを並行して開始、制御、または停止できるようにするイベント駆動型の機能です。ここでは、systemd 機能にカスタム スクリプトを追加する方法について説明します。
1.カスタム スクリプトの記述とデバッグ
通常、systemd スクリプトはシェル スクリプトとして記述されます。通常の規則を使用してカスタム スクリプトを作成することから始めます。スクリプトを my-custom-script.sh と呼びますが、これは簡単です:
#!/bin/sh echo "I am a custom script" > /var/tmp/script.out echo "The script was run at : `date`" >> > /var/tmp/script.out
スクリプトは実行可能でなければなりません。
# chmod 0755 /var/tmp/my-custom-script.sh
2.カスタム スクリプトを systemd に記述する
スクリプトを手動で記述してテストすると、スクリプトを systemd システムに記述する準備が整います。これを行うには、[name].service ファイルが必要です。構文は、構成ファイルに一般的に使用される INI 形式を使用します。例を続けると、my-custom-script.service ファイルが必要です。実行可能ファイルは、サービスが開始されるたびに 1 回だけ実行されます。ネットワーク層が稼働して安定するまで、サービスは開始されません。
以下の内容で /etc/systemd/system/my-custom-script.service に新しいサービス ユニット ファイルを作成します。サービス ユニットの名前はユーザーが定義し、任意の名前にすることができます。
# This is my-custom-script.service, which describes the my-custom-script.sh file [Unit] Description=This is executed on shutdown or reboot DefaultDependencies=no Wants=network-pre.target # (if network is required before running the script) Before=network-pre.target shutdown.target reboot.target halt.target # Defines the order in which units are stoped. #(REQUIRED) [Service] Type=oneshot # enables specifying multiple custom commands that are then executed sequentially. (REQUIRED) RemainAfterExit=true # required by the oneshot setting (REQUIRED) Environment=ONE='one' "TWO='2" # you can set some environment variables, that may be necessary to pass as arguments ExecStart=/bin/true # because is a shutdown script nothing is done when this service is started ExecStop=/bin/bash /var/tmp/my-custom-script.sh ${ONE} ${TWO} # < --*********** change to the script full path ************ (REQUIRED) TimeoutStopSec=1min 35s # Configures the time to wait for stop. [Install] WantedBy=multi-user.target # When this unit is enabled, the units listed in WantedBy gain a Want dependency on the unit. (REQUIRED)
3.今後の再起動のためにスクリプトを有効にする
以前のバージョンの chkconfig と同様に、サービスを有効にする必要があります。新しいサービスが追加されたため、systemd デーモンに自身を再構成するよう通知します。
# systemctl enable my-custom-script.service # systemctl daemon-reload