Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 開機自啟動配置全解析:SysVinit、systemd、rc.local 與 systemd 服務單元

編輯:Linux 教學

Linux 開機自啟動機制隨發佈版演進已有多代:傳統 SysVinit (rc.d)、systemd 服務單元、用戶級 Shell 配置、定時任務等。本文系統梳理各層級配置方法,適用於 CentOS 6/7、Ubuntu 16.04+、Debian 9+ 等主流環境。

一、系統級服務管理(推薦使用 systemd)

systemd 服務單元(現代標準)

# 建立服務文件 /etc/systemd/system/myservice.service
[Unit]
Description=My Custom Service
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/myapp --config /etc/myapp.conf
Restart=on-failure
User=nobody

[Install]
WantedBy=multi-user.target

管理命令:

  • systemctl daemon-reload:重載配置
  • systemctl enable myservice:設定開機自啟
  • systemctl start myservice:立即啟動
  • systemctl status myservice:查看狀態

SysVinit 兼容層 (chkconfig / update-rc.d)

  • CentOS 6:chkconfig --level 35 myservice on
  • Debian/Ubuntu:update-rc.d myservice defaults
  • 腳本放置 /etc/init.d/,需符合 LSB 標準(支援 start/stop/restart/status)

二、簡易腳本自啟:/etc/rc.local(兼容舊習慣)

大多數發佈版仍支援 /etc/rc.d/rc.local 或 /etc/rc.local(轉鏈)。

chmod +x /etc/rc.d/rc.local
echo "/usr/local/bin/startup.sh" >> /etc/rc.d/rc.local

注意:systemd 系統下需確保 rc-local.service 已啟用。

三、用戶級自啟動(登入時執行)

文件生效範圍說明
~/.bash_profile登入 Shell首選,僅登入時執行一次
~/.bashrc互動式 Shell每開啟終端執行,常放別名/函數
~/.profile圖形登入非 Bash 登入 Shell 回退讀取
/etc/profile所有用戶系統級環境變數,登入時執行

例:echo "synergyc 192.168.0.154" >> ~/.bash_profile

四、定時任務替代方案

cron 週期性任務

crontab -e
# 每天 03:00 備份
0 3 * * * /scripts/backup.sh >> /var/log/backup.log 2>&1

systemd Timer(現代替代 cron)

# /etc/systemd/system/backup.timer
[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

配合同名 .service 啟用:systemctl enable --now backup.timer

at 單次延遲執行

echo "/scripts/onetime.sh" | at 23:59
atq              # 查看隊列
atrm 1           # 刪除任務

五、圖形界面自啟動

  • GNOME/KDE:~/.config/autostart/*.desktop
  • 系統級:/etc/xdg/autostart/

六、常見坑點避雷

  • 環境變數缺失:服務中使用絕對路徑,或在 Service 區塊設定 Environment=PATH=...
  • 網路未就緒:加 After=network-online.target + Wants=network-online.target
  • 權限不足:指定 User= Group=,避免 root 執行
  • 依賴順序:systemd 並行啟動,必須顯式聲明 After= Requires=

總結:系統服務用 systemd,用戶腳本用 ~/.bash_profile,定時任務用 systemd timer/cron,圖形程序用 .desktop,按場景選型最穩健。

Copyright © Windows教程網 All Rights Reserved