1、編寫腳本
編寫一個 /opt/hello.sh 腳本
sudo vim /opt/hello.sh
#!/bin/bash
while true
do
echo hello world >> /tmp/hello.log
sleep 1
done
賦予執行權限。
sudo chmod 0755 /opt/hello.sh
2、在/etc/systemd/system/ 下創建Unit定義文件
sudo vim /etc/systemd/system/hello.service
內容如下
[Unit]
Description = hello daemon
[Service]
ExecStart = /opt/hello.sh
Restart = always
Type = simple
[Install]
WantedBy = multi-user.target
ExecStart中填寫想要執行的腳本。
Restart = always 是指進程或服務意外故障的時候可以自動重啟的模式。
※Unit文件的詳細寫法會另外給出。
(Type = simple 指默認的選項沒有必要填寫,或可理解成其余選項均為系統默認。)
3、把Unit添加進Service
使用systemctl list-unit-files --type=service
命令,出現如下圖所示即為正常。
$ sudo systemctl list-unit-files --type=service | grep hello
hello.service disabled
OK!
4、enable服務后使之start
之后系統將以一般服務的形式對待它。
# 開機自啟動on
$ sudo systemctl enable hello
# 單次啟動
$ sudo systemctl start hello
運行狀態確認
$ sudo systemctl status hello
hello.service - hello daemon
Loaded: loaded (/etc/systemd/system/hello.service; enabled)
Active: active (running) since 2018-05-19 09:02:19 UTC; 2min 54s ago
Main PID: 551 (hello.sh)
CGroup: /system.slice/hello.service
├─ 551 /bin/bash /opt/hello.sh
└─2062 sleep 1
6月 19 09:02:19 localhost.localdomain systemd[1]: Started hello daemon.
打開日志文件看看腳本是否正常運作。
[vagrant@localhost ~]$ tailf /tmp/hello.log
hello world
hello world
hello world
hello world
hello world
成功了!
5、重啟機器,查看服務是否正常自動啟動
$ sudo reboot
重啟后,如正常顯示hello服務即為操作政工。
本文來自投稿,不代表Linux運維部落立場,如若轉載,請注明出處:http://www.www58058.com/100909