Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux 關機重啟命令大全:shutdown、reboot、halt、poweroff、init 參數詳解與最佳實踐

編輯:Linux 系統常見問題解答

Linux 提供多種關機重啟命令,參數豐富、行為微妙不同。本文系統梳理 shutdown、reboot、halt、poweroff、init 的用法、底層流程、常見陷阱,給出生產環境標準化操作建議。

命令對比速查

命令主要用途關鍵參數典型場景
shutdown標準、安全、支持定時/廣播/取消-h 關機 -r 重啟 +m 分鐘 hh:mm 時刻 -c 取消 -k 僅廣播生產環境首選,計劃性維護
reboot立即重啟-f 強制(不調用 shutdown) -p 關機 --halt 停機緊急重啟、腳本自動化
halt停機(默認不斷電)-p 斷電 -f 強制 -n 不同步單用戶模式下停機
poweroff關機斷電同 halt物理機關機
init 0/6切換運行級別 0(關機) 6(重啟)無參數SysVinit 習慣、極簡腳本

關機/重啟底層流程(Systemd 現代視角)

  1. 同步文件系統:sync 將內存緩存刷入磁盤(shutdown 自動執行,reboot -f 跳過)。
  2. 記錄事件:寫入 /var/log/wtmp、/var/run/utmp(last reboot 可見)。
  3. 發送信號:SIGTERM → 等待 TimeoutStopSec(默認 90s) → SIGKILL 強制終止所有進程。
  4. 停止服務:按依賴逆序停止 systemd units。
  5. 卸載文件系統:umount -a 唯讀重掛載根分區。
  6. 執行 ACPI:關機調用 kernel_power_off,重啟調用 kernel_restart。

常用範例

# 立即關機
shutdown -h now
poweroff
init 0

# 立即重啟
shutdown -r now
reboot
init 6

# 定時關機(2:30 AM,廣播通知在線用戶)
shutdown -h 02:30 'Scheduled maintenance'

# 10 分鐘後重啟
shutdown -r +10 'Kernel upgrade requires reboot'

# 僅發送警告不關機
shutdown -k now 'Test broadcast'

# 取消已排程的關機/重啟
shutdown -c

# 關機前同步數據(良好習慣)
sync; sync; shutdown -h now

關機前檢查清單(生產環境必做)

  1. 觀察系統狀態:who(在線用戶)、netstat -an/ss -an(網絡連接)、ps aux(關鍵進程)。
  2. 通知相關方:shutdown -k +5 'System will reboot in 5 minutes for kernel patch' 或發送郵件/工單/群消息。
  3. 確認備份完成:數據庫備份、配置文件歸檔、快照創建。
  4. 選擇正確命令:區分關機(-h)與重啟(-r),注意 now vs +m vs hh:mm。
  5. 數據同步:手動 sync 確保緩存落盤(雖然 shutdown 會做,但雙重保險)。

查看重啟歷史

last reboot
last -x | grep -E 'reboot|shutdown'
# 輸出示例:
# reboot   system boot  3.10.0-1160.el7  Tue Jan 10 03:15   still running
# reboot   system boot  3.10.0-1127.el7  Mon Jan  9 02:30 - 03:15  (00:45)

遠程執行關機/重啟

# SSH 遠程執行(需免密或 sshpass)
ssh root@server 'shutdown -r now'
ssh root@192.168.1.100 '/sbin/shutdown -r now'

# 批量並行(Ansible 範例)
ansible all -m reboot -a "reboot_timeout=300"

特殊場景處理

  • 系統凍結無響應:嘗試 Alt+SysRq+R E I S U B(魔法鍵安全重啟),最後手段長按電源鍵強制斷電。
  • 單用戶模式下:halt -p 或 poweroff 直接斷電。
  • 容器內:shutdown/reboot 通常被阻塞或僅停止容器進程,宿主機不受影響。
  • KVM 虛擬機:virsh shutdown/virsh reboot 發送 ACPI 信號,客體機需安裝 acpid 服務。

口訣: 計劃用 shutdown、緊急用 reboot、物理機關機用 poweroff、查歷史用 last reboot、動手前先 sync 再通知再確認。

Copyright © Windows教程網 All Rights Reserved