自定義服務需提供符合 LSB (Linux Standard Base) 規範的初始化腳本,放置於 /etc/rc.d/init.d/ (或 /etc/init.d/),具備:
chmod +x /etc/rc.d/init.d/myservicestart、stop、restart、status#!/bin/bash
# chkconfig: 35 80 20
# description: My custom service daemon
# processname: myservice
# config: /etc/myservice.conf
# pidfile: /var/run/myservice.pid
start() { ... }
stop() { ... }
case "$1" in
start) start ;;
stop) stop ;;
restart) stop; start ;;
status) status myservice ;;
*) echo "Usage: $0 {start|stop|restart|status}"; exit 1 ;;
esac
| 操作 | 命令 | 說明 |
|---|---|---|
| 添加服務 | chkconfig --add myservice | 將腳本註冊至系統服務列表,建立 /etc/rc.d/rc[0-6].d/ 符號連結 |
| 刪除服務 | chkconfig --del myservice | 移除所有運行級別符號連結,服務不再被 chkconfig 管理 |
| 設定自啟動 | chkconfig --level 35 myservice on | 在級別 3 (多用戶文字) 和 5 (圖形) 設為自啟動 (建立 S80myservice 連結) |
| 關閉自啟動 | chkconfig --level 35 myservice off | 移除級別 3、5 的啟動連結 (保留 K20myservice 關機連結) |
| 查看狀態 | chkconfig --list myservice | 顯示各運行級別狀態:myservice 0:off 1:off 2:on 3:on 4:on 5:on 6:off |
| 立即啟動/停止 | service myservice start/stop/restart/status | 操作當前運行實例,不影響自啟動設定 |
| 級別 | 名稱 | 適用場景 |
|---|---|---|
| 0 | 關機 | 系統停止 |
| 1 | 單用戶 | 維護模式 |
| 2 | 多用戶無網路 | 少用 |
| 3 | 多用戶文字 | **伺服器標準運行級別** |
| 4 | 保留 | 用戶自定義 |
| 5 | 多用戶圖形 | 桌面環境 |
| 6 | 重啟 | 系統重啟 |
現代發行版已全面轉用 systemd,chkconfig 為相容保留,建議直接使用 systemctl:
| chkconfig 命令 | systemctl 對應 |
|---|---|
chkconfig --add myservice | systemctl daemon-reload (放置 unit 檔於 /etc/systemd/system/) |
chkconfig --del myservice | systemctl disable --now myservice; rm /etc/systemd/system/myservice.service |
chkconfig --level 35 myservice on | systemctl enable myservice (預設 multi-user.target + graphical.target) |
chkconfig --level 35 myservice off | systemctl disable myservice |
chkconfig --list myservice | systemctl is-enabled myservice; systemctl status myservice |
service myservice start | systemctl start myservice |
# 1. 編寫腳本 /etc/init.d/mydaemon
# 2. 賦權
chmod +x /etc/init.d/mydaemon
# 3. 註冊
chkconfig --add mydaemon
# 4. 設定自啟動 (級別 3,5)
chkconfig --level 35 mydaemon on
# 5. 驗證
chkconfig --list mydaemon
# 輸出: mydaemon 0:off 1:off 2:off 3:on 4:off 5:on 6:off
# 6. 立即啟動
service mydaemon start
# 7. 查看狀態
service mydaemon status
yum install -y initscripts (systemd 系統用 systemctl)。# chkconfig: 註解行、無執行權限、路徑錯誤。/etc/rc.d/rc3.d/S80myservice 符號連結是否存在、腳本 start 函數是否正確返回 0。.service unit 會優先被 systemd 接管,chkconfig 操作可能無效。chkconfig 是 SysV init 時代的服務管理核心工具,掌握 --add/--del/--level/--list 四大操作,配合 service 即時控制,能完整掌控服務生命週期。現代系統請轉用 systemctl,但理解 chkconfig 邏輯有助於遷移舊服務與排查相容性問題。