萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

SysV 服務管理腳本撰寫規範與實戰範例

SysV init 最大特色是每項服務擁有獨立腳本,支援 start、stop、restart、status 等標準動作。本文說明標準骨架結構,並以 LFS swap 腳本為例實戰演練。

標準腳本骨架

#!/bin/sh
# 來源通用函數與變數
. /etc/sysconfig/rc
. ${rc_functions}

case "${1}" in
start)
    # 啟動邏輯
    ;;
stop)
    # 停止邏輯
    ;;
restart)
    ${0} stop
    sleep 1
    ${0} start
    ;;
status)
    # 狀態查詢
    ;;
*)
    echo "Usage: ${0} {start|stop|restart|status}"
    exit 1
    ;;
esac

實戰範例:swap 服務腳本

#!/bin/sh
. /etc/sysconfig/rc
. ${rc_functions}

case "${1}" in
start)
    boot_mesg "Activating all swap files/partitions..."
    swapon -a
    evaluate_retval
    ;;
stop)
    boot_mesg "Deactivating all swap files/partitions..."
    swapoff -a
    evaluate_retval
    ;;
restart)
    ${0} stop
    sleep 1
    ${0} start
    ;;
status)
    boot_mesg "Retrieving swap status." ${INFO}
    echo_ok
    echo
    swapon -s
    ;;
*)
    echo "Usage: ${0} {start|stop|restart|status}"
    exit 1
    ;;
esac

關鍵點解析

  • boot_mesg、evaluate_retval、echo_ok 來自 rc_functions,提供統一的開機訊息格式與返回碼檢查。
  • swapon -a / swapoff -a 依 /etc/fstab 掛載/卸載所有 swap 區。
  • status 動作呼叫 swapon -s 顯示目前 swap 使用摘要。
  • ${0} 代表腳本自身路徑,支援 restart 串聯。

撰寫檢核清單

  1. Shebang 指定 #!/bin/sh (POSIX 相容)。
  2. 引入 rc_functions 取得統一輸出函數。
  3. 使用 case 分派 $1,涵蓋 start|stop|restart|status。
  4. 錯誤處理:檢查指令返回碼 $?,非零時呼叫 print_error_msg。
  5. 支援 IN_BOOT=1 環境變數區分開機與手動執行情境。
  6. 腳本放置於 /etc/rc.d/init.d/,並以 S##name/K##name 符號連結至對應 rcX.d。

現代替代方案

systemd 系統請撰寫 .service 單元檔,但理解 SysV 腳本仍有助於維護舊系統、容器入口腳本或嵌入式環境。

copyright © 萬盛學電腦網 all rights reserved