cd /etc/init.d
vim myservice.sh
#!/bin/bash
# chkconfig: 2345 70 30
# description: My custom service description
# processname: myservice
# 必須:載入環境變數 (系統啟動時尚未載入 /etc/profile)
source /etc/profile
start() {
echo "Starting myservice..."
/usr/local/bin/myservice --daemon
}
stop() {
echo "Stopping myservice..."
killproc myservice
}
case "$1" in
start) start ;;
stop) stop ;;
restart) stop; start ;;
status) status myservice ;;
*) echo "Usage: $0 {start|stop|restart|status}" ;;
esac
# chkconfig: 2345 70 30
# 2345 : 運行等級 2,3,4,5 啟動 (3=多用戶文字, 5=圖形介面)
# 70 : 啟動順序號 (數字越小越早啟動,依賴服務需更小)
# 30 : 關機停止順序號 (數字越小越早停止)
chmod +x /etc/init.d/myservice.sh
chkconfig --add myservice
chkconfig myservice on
# 驗證
chkconfig --list myservice
# myservice 0:off 1:off 2:on 3:on 4:on 5:on 6:off
vim /etc/systemd/system/myservice.service
[Unit]
Description=My Custom Service
After=network.target
Wants=network.target
[Service]
Type=simple
EnvironmentFile=-/etc/sysconfig/myservice
ExecStart=/usr/local/bin/myservice --daemon
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=myservice
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl enable myservice
systemctl start myservice
systemctl status myservice
# 開機自啟
systemctl enable myservice
# 查看日誌
journalctl -u myservice -f
SysV init 腳本中 必須 手動 source /etc/profile,因為啟動時環境變數尚未載入。Systemd 透過 EnvironmentFile 或 Environment= 顯式宣告。
| 功能 | SysV init | Systemd |
|---|---|---|
| 啟動 | service myservice start | systemctl start myservice |
| 停止 | service myservice stop | systemctl stop myservice |
| 重啟 | service myservice restart | systemctl restart myservice |
| 狀態 | service myservice status | systemctl status myservice |
| 啟用開機自啟 | chkconfig myservice on | systemctl enable myservice |
| 停用開機自啟 | chkconfig myservice off | systemctl disable myservice |
| 查看狀態 | chkconfig --list | systemctl list-unit-files |