LoginSignup
1
0

More than 1 year has passed since last update.

Linux: 自作サービスをsystemdに登録して自動起動させてみた

Posted at

新しいソフトウェアをインストールした際に使用したのでメモ。

実施環境:
Linux
[root@testhost ~]# uname -a
Linux testhost 4.18.0-331.el8.x86_64 #1 SMP Thu Aug 19 16:49:03 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
[root@testhost ~]# echo $SHELL
/bin/bash

Linux においてサービスの自動起動を行う方法はいくつかあります。
かつては sysVinit が有名でしたが、最近の主流は systemd を用いたものとなっています。
そこで、以下の自作のスクリプトを自動起動に登録してみます。

/usr/local/test/test.sh
#!/bin/bash

while true
do
    sleep 10
done

exit 0

まず、 /usr/lib/systemd/system 内に設定ファイルを作成し、以下のように書き込みます。
ファイル名は拡張子が .service であれば何でも良いのですが、今回は test.service としました。

/usr/lib/systemd/system/test.service
[Unit]
Description = TEST

[Service]
ExecStart   = /usr/local/test/test.sh
Type        = simple

[Install]
WantedBy    = default.target

上記のファイル内の項目については以下の通りです。他にも細かい設定はありますが、今回は割愛します。

  • Description:サービスの説明。今回は TEST としましたが、わかれば何でも良いです。

  • ExecStart:サービスの起動コマンド。フルパスで、引数が必要な場合は引数も含めて記載してください。

  • Type:サービスの起動タイプ。今回は実行したコマンド(スクリプト)自体が起動し続けるタイプなので simple となります。コマンド自体は終了し子プロセスが生き続けるタイプの場合は forking を指定してください。

  • WantedBy:サービスが自動起動する環境。CUI( multi-user.target )の場合だけでもよいですが、基本全環境( default.target )でよいかと思います。

次に、 systemctl daemon-reload を実行し設定ファイルの再読み込みを行います。
この時点で、自作のスクリプトを systemd から管理できるようになっています。

Linux
[root@testhost ~]# systemctl daemon-reload
[root@testhost ~]# systemctl start test.service
[root@testhost ~]# systemctl is-active test.service
active

では、いよいよこのスクリプトを自動起動の対象に設定します。
そのためには、 systemctl enable <サービス名>.service を実行します。
systemctl is-enabled <サービス名>.service を実行して enabled と表示されれば登録済みです。

Linux
[root@testhost ~]# systemctl enable test.service
Created symlink /etc/systemd/system/default.target.wants/test.service → /usr/lib/systemd/system/test.service.
[root@testhost ~]# systemctl is-enabled test.service
enabled

早速OSを再起動し、サービスが自動起動していることを確認してみてください。

Linux(再起動後)
[root@testhost ~]# systemctl is-active test.service
active
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0