systemd 的服務程序基礎入門可以參考如下鏈接:
http://www.ruanyifeng.com/blog/2016/03/systemd-tutorial-commands.html
http://www.ruanyifeng.com/blog/2016/03/systemd-tutorial-part-two.html
這裏是一個簡單的例子(hello 級別),實戰操作幫助理解上述概念
首先要有一個準備運行的後臺服務程序,然後是該服務程序的配置文件,告訴systemd該如何啓動這個程序。
1. 先準備一個服務程序hello.sh,用來在後臺運行
$ cat /opt/hello.sh
#!/bin/bash
while true
do
echo "hello world" >> /tmp/hello.log
sleep 1
done
我們把hello.sh 放到了/opt 目錄下,你可以隨便放置到你喜歡的地方
2. 書寫一個服務配置文件,讓systemd知道該如何啓動這個程序
這個程序按照慣例放到/etc/systemd/system 目錄下:
它一般包含3個部分,Unit(單元描述),Service(服務描述),Install(安裝描述)
cat /etc/systemd/system/hello.service
[Unit]
Description = hello daemon
[Service]
ExecStart = /opt/hello.sh
Restart = always
Type = simple
[Install]
WantedBy = multi-user.target
[Unit]是單元描述信息,啓動順序,依賴關係等。
[Service]說明啓動程序是什麼?類型是什麼? 如何啓動
[Install] 說明安裝到那裏.
3. 實戰操作
立即啓動: sudo systemctl start hello.service #將會調用ExecStart 所指程序
立即停止: sudo systemctl stop hello.service #服務管理若無ExedStop, 執行默認操作
查看狀態: sudo systemctl status hello.service
查看結果: 該程序當然是看 /tmp/hello.log
加入到開機啓動: sudo systemctl enable hello.service
Created symlink from /etc/systemd/system/multi-user.target.wants/hello.service to /etc/systemd/system/hello.service.
取消開機啓動: sudo systemctl diable hello.service
Removed symlink /etc/systemd/system/multi-user.target.wants/hello.service.
練習: svn 服務每次重新啓動機器時都需要手動調用
/usr/bin/svnserve -d -r /home/dell1/depot
來啓動,試寫成服務開機啓動.
答:仿照helloworld.service.
cat svn.service
[Unit]
Description = svn daemon
[Service]
ExecStart = /usr/bin/svnserve -d -r /home/dell1/depot
Type = forking
[Install]
WantedBy = multi-user.target
只所以用forking, 因爲simple 主進程會退出而成爲inactive 狀態,所以告訴systemd是forking.