Systemd
是最初由Red Hat Linux團隊開發的Linux系統工具。 它包括許多功能,包括用於啓動和管理系統進程的引導系統。 當前,它是大多數Linux發行版中的默認初始化系統。 許多常用的軟件工具(例如SSH和Apache)都附帶有systemd服務,其成套封裝使用起來相當方便,且併發啓動大大增加了啓動速度。
創建自定義systemd系統服務
1、新建example腳本helloworld.sh,輸入以下內容:
DATE=`date '+%Y-%m-%d %H:%M:%S'`
echo "Example service started at ${DATE}"
echo "HelloWorld..."
2、腳本拷貝到/usr/bin路徑,並賦予可執行權限:
sudo cp helloworld.sh /usr/bin/helloworld.sh
sudo chmod +x /usr/bin/helloworld.sh
3、在/lib/systemd/system/路徑下新建文件(服務),文件名爲helloworld.service:
[Unit]
Description=Example HelloWorld systemd service.
[Service]
Type=simple
ExecStart=/bin/bash /usr/bin/hellworld.sh
[Install]
WantedBy=multi-user.target
4、將 helloworld.service文件拷貝到/etc/systemd/system目錄:
sudo cp /lib/systemd/system/helloworld.service /etc/systemd/system/helloworld.service
sudo chmod 644 /etc/systemd/system/helloworld.service
詳細的systemd規則可以參考systemd documentation。
使能自定義systemd服務
1、一旦創建了service就可以用一下命令測試:
sudo systemctl start helloworld
2、 檢查服務狀態:
sudo systemctl status helloworld
輸出結果如下:
● helloworld.service - Example HelloWorld systemd service.
Loaded: loaded (/etc/systemd/system/helloworld.service; disabled; vendor preset: enabled)
Active: inactive (dead)
5月 15 23:32:07 gohi-pc bash[3974]: HelloWorld...
5月 15 23:32:07 gohi-pc systemd[1]: helloworld.service: Succeeded.
5月 15 23:33:15 gohi-pc systemd[1]: Started Example HelloWorld systemd service..
5月 15 23:33:15 gohi-pc helloworld.sh[3997]: Example service started at 2020-05-15 23:33:15
5月 15 23:33:15 gohi-pc helloworld.sh[3997]: HelloWorld...
5月 15 23:33:15 gohi-pc systemd[1]: helloworld.service: Succeeded.
5月 15 23:37:14 gohi-pc systemd[1]: Started Example HelloWorld systemd service..
5月 15 23:37:14 gohi-pc bash[4279]: Example service started at 2020-05-15 23:37:14
5月 15 23:37:14 gohi-pc bash[4279]: HelloWorld...
5月 15 23:37:14 gohi-pc systemd[1]: helloworld.service: Succeeded.
3、最後將服務enable:
sudo systemctl enable helloworld
輸出如下:
Created symlink /etc/systemd/system/multi-user.target.wants/helloworld.service → /etc/systemd/system/helloworld.service.