1. 程式人生 > >Linux 下如何新增開機自啟動檔案

Linux 下如何新增開機自啟動檔案

【導讀】

Linux系統在啟動的過程中,會先啟動核心,通過核心初始化所有的裝置。在初始化完這些裝置後,會執行一個叫“rc.local”的檔案,它是進入系統前最後執行的一個檔案,主要用於定義一些需要在進入系統前,所需要啟動的指令碼程式。所以通過編輯該檔案可以實現自啟動的功能。

具體操作

該檔案存放於根目錄下的 /etc/ 資料夾中,通過編輯該檔案,在檔案中 exit 0 語句的前面加入執行語句,即可實現自啟動。

例如:開機時,附帶啟動/home/目錄下的 test.py 檔案,操作如下:

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
  printf "My IP address is %s\n" "$_IP"
fi

python3 /home/test.py

exit 0

在檔案中,加入 python3 /home/test.py 即可!

PS:在定義中,需要指定執行的檔案解析器,由於這裡啟動的是 .py 檔案,所以需要呼叫 python3 解析器來執行該檔案。