Login

Navigation

This articles is published 1059 days ago and last updated 1030 days ago, some information may be out of date.

Linux開機啟動多種辦法

簡言:
重啟Linux系統後免於手動啟動對應的程式或內容,可以用幾下幾種方式實現開機自啟動。

開機啟動辦法:
Crontab 任務:
crontab 在系統中有一個運行著的守護進程,當系統時間符合某一條規劃記錄時, 守護進程就會啟動相應的任務。可以通過crontab -e來查看任務。
    @reboot /usr/local/script.sh
使用@reboot 選項來設置開機啟動「script.sh」腳本。
/etc/rc.local 加入啟動指命:
你想設置和啟動的東西(如指令或腳本)放到「exit 0」之前
# Put your custom commands here that should be executed once
# the system init finished. By default this file does nothing.

sh /etc/init.d/mount.sh

exit 0
這段內容是設置開機啟動「mount.sh」腳本。
/etc/init.d 啟動腳本:
實現服務的啟動、關閉與觀察等方式:
  • 啟動:
/etc/init.d/daemon start
  • 關閉:
/etc/init.d/daemon stop
  • 重新啟動:
/etc/init.d/daemon restart
  • 狀態觀察:
/etc/init.d/daemon status
Systemd 服務:
Systemd 是 Linux 系統工具,用來啟動守護進程

可實現的優點:

  • 平行處理所有服務,加速開機流程。
  • 一經要求就回應的 on-demand 啟動方式。
  • 服務相依性的自我檢查。
  • 依 daemon 功能分類。
  • 將多個 daemons 集合成為一個群組。
  • 向下相容舊有的 init 服務腳本。

建立系統啟動服務

建立一個系統服務 /etc/systemd/system/my-service.service
[Unit]
Description=My custom startup script
# After=network.target
# After=systemd-user-sessions.service
# After=network-online.target

[Service]
# User=spark
# Type=simple
# PIDFile=/run/my-service.pid
ExecStart=/home/user/startup.sh start
# ExecReload=/home/user/startup.sh reload
# ExecStop=/home/user/startup.sh stop
# TimeoutSec=30
# Restart=on-failure
# RestartSec=30
# StartLimitInterval=350
# StartLimitBurst=10

[Install]
WantedBy=multi-user.target

去掉註解#

[Unit]
Description=My custom startup script

[Service]
ExecStart=/home/user/startup.sh start

[Install]
WantedBy=multi-user.target

Service Unit 常用命令

開機啟動

systemctl enable daemon

關閉開機啟動

systemctl disable daemon

啟動服務

systemctl start daemon

停止服務

systemctl stop daemon

重啟服務

systemctl restart daemon

查看服務狀態

systemctl status daemon

結束服務進程(服務無法停止時)

systemctl kill daemon

結語:
在多種方法中建議使用Systemd 的系統啟動服務,因為Systemd 已成為大多數發行版的標準配置。

參考資料:

鳥哥的 Linux 私房菜