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
#!/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 串聯。#!/bin/sh (POSIX 相容)。rc_functions 取得統一輸出函數。case 分派 $1,涵蓋 start|stop|restart|status。$?,非零時呼叫 print_error_msg。IN_BOOT=1 環境變數區分開機與手動執行情境。/etc/rc.d/init.d/,並以 S##name/K##name 符號連結至對應 rcX.d。systemd 系統請撰寫 .service 單元檔,但理解 SysV 腳本仍有助於維護舊系統、容器入口腳本或嵌入式環境。