linux設置開機啓動有幾種方法
設置linux開機啓動有3種方法
1. 編輯rc.loacl腳本
linux在開機啓動的時候會運行/etc/rc.local
#!/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
##在 下面添加要開機啓動的程序和腳本即可
sudo nohup /home/pi/frp/start.sh &
## 注意的地方是,要加上&,讓程序在後臺運行,如果你的程序是死循環那種,就進不去系統了,儘量也加上nohup。
exit 0
這個方法,雖然簡單,但是我發現不是所有程序都能這樣,放到啓動腳本中就能開機啓動,我曾經寫過幾個程序進行開機啓動設置,但發現開機後程序並沒有運行起來,這就是讓我很納悶的原因,下面是我從網上找的分析原因,但經過測試還是無法開機啓動。
- /etc/rc.local沒有執行權限,修改權限之後,還是無法解決(網上有人說可以)
- 路徑沒有編寫絕對路徑(這個有可能,但是發現絕對路徑正確了,我的程序還是沒有開機啓動)
- sh兼容性問題,重新進行軟鏈接(參考https://www.mmuaa.com/post/4e728a88a1a68e13.html)
最後都沒運行起來。然後我猜想,是不是因爲系統其實還沒有完全跑起來。到時我的程序不能運行,基於這一點,我做了一下延時
sleep(10)
sudo nohup /home/pi/frp/start.sh &
果然這次程序運行起來了,雖然沒有發現真正的原因。暫時沒發現有程序沒有跑起來,暫時這麼解決。
2. 把程序添加爲系統服務
2.1 創建程序的系統文件
cd /usr/lib/systemd/system
sudo nano frp.service #命名按照**.service定義
複製一下內如
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target
#對你程序的描述
[Service]
Type = simple #參看下面給出的鏈接
ExecStart = /home/pi/frp/frpc -c /home/pi/frp/frpc.ini #修改爲你程序的絕對路徑即可
下面是官網系統程序配置解釋
https://www.freedesktop.org/software/systemd/man/systemd.service.html
2.2 設置開機啓動
sudo systemctl disable frpc
sudo systemctl enable frpc
sudo systemctl start frpc
3. 不好用的方法
新建bash腳本放在/etc/profile.d,此文件爲系統的每個用戶設置環境信息。
當用戶第一次登錄時,該文件被執行. 並從/etc/profile.d目錄的配置文件中搜集shell的設置。