Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 服務管理實戰:chkconfig 添加、刪除、自啟動與狀態查詢

編輯:Linux 教學

服務腳本規範

自定義服務需提供符合 LSB (Linux Standard Base) 規範的初始化腳本,放置於 /etc/rc.d/init.d/ (或 /etc/init.d/),具備:

  • 可執行權限:chmod +x /etc/rc.d/init.d/myservice
  • 支援參數:start、stop、restart、status
  • 標註運行級別與描述 (chkconfig 讀取):
#!/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)

操作命令說明
添加服務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 時代的對應 (RHEL 7+/CentOS 7+)

現代發行版已全面轉用 systemd,chkconfig 為相容保留,建議直接使用 systemctl:

chkconfig 命令systemctl 對應
chkconfig --add myservicesystemctl daemon-reload (放置 unit 檔於 /etc/systemd/system/)
chkconfig --del myservicesystemctl disable --now myservice; rm /etc/systemd/system/myservice.service
chkconfig --level 35 myservice onsystemctl enable myservice (預設 multi-user.target + graphical.target)
chkconfig --level 35 myservice offsystemctl disable myservice
chkconfig --list myservicesystemctl is-enabled myservice; systemctl status myservice
service myservice startsystemctl 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

常見問題

  • service 命令找不到:yum install -y initscripts (systemd 系統用 systemctl)。
  • chkconfig --add 失敗:腳本缺少 # chkconfig: 註解行、無執行權限、路徑錯誤。
  • 自啟動不生效:檢查 /etc/rc.d/rc3.d/S80myservice 符號連結是否存在、腳本 start 函數是否正確返回 0。
  • systemd 並存衝突:同名 .service unit 會優先被 systemd 接管,chkconfig 操作可能無效。

結語

chkconfig 是 SysV init 時代的服務管理核心工具,掌握 --add/--del/--level/--list 四大操作,配合 service 即時控制,能完整掌控服務生命週期。現代系統請轉用 systemctl,但理解 chkconfig 邏輯有助於遷移舊服務與排查相容性問題。

Copyright © Windows教程網 All Rights Reserved