環境:Fedora 7,root 管理員,普通用戶 test1。目標:開機自動以 test1 身分執行 /home/test1/test.py(每次執行向 test.log 追加時間戳記)。
編輯 /etc/rc.d/rc.local 末尾加入:
cd /home/test1
su test1 -c "python /home/test1/test.py"
cd 切換工作目錄,否則 Python 找不到 test.log 報權限錯誤。su -c 將命令作為參數傳遞,避免開啟子 Shell 導致後續指令卡住。建立 /etc/rc.d/init.d/mystart:
#!/bin/bash
# chkconfig: 2345 80 05
# description: mystart service
RETVAL=0
start() {
echo -n "mystart service ..."
cd /home/test1
su test1 -c "python /home/test1/test.py"
}
stop() {
echo "mystart service is stopped..."
}
case $1 in
start) start ;;
stop) stop ;;
esac
exit $RETVAL
啟用步驟:
chmod +x /etc/rc.d/init.d/mystartchkconfig --add mystartchkconfig --list mystart 確認錯誤寫法:
su test1
cd /home/test1
python test.py
exit
原因:su test1 開啟子 Shell,後續指令需等子 Shell 結束才執行,而 Python 長期運行導致啟動流程卡死。正確做法皆為 su user -c "command" 單行傳遞。