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

使用 nohup 讓 Linux 程式在後台持續運行

編輯:Linux 教學

問題背景

普通命令加 & 放入後台,關閉終端會收到 SIGHUP 信號導致進程終止。需脫離終端獨立運行。

nohup 基本用法

nohup 命令 [參數] &

實戰範例

# 後台運行 PHP 腳本
nohup /root/test.php &
# 提示:appending output to nohup.out

# 指定輸出文件
nohup /root/test.php > mylog.log 2>&1 &

# 後台運行 MySQL (守護進程本身不需 nohup)
/usr/local/mysql/bin/mysqld_safe --user=mysql &

輸出重定向說明

  • 預設輸出追加至當前目錄 nohup.out
  • 不可寫時轉向 $HOME/nohup.out
  • 2>&1 將 stderr 合併至 stdout

查看與管理後台任務

jobs              # 列出當前 Shell 的後台任務
fg %1             # 將任務 1 調回前台
bg %1             # 讓暫停任務 1 在後台繼續
kill %1           # 終止任務 1

進階替代方案

  • systemd 服務:生產環境推薦寫 .service 文件,systemctl start 管理
  • screen/tmux:虛擬終端會話,斷線重連保持運行
  • supervisor:進程監控工具,自動重啟、日誌輪轉

nohup 參考手冊摘要

用途:忽略 SIGHUP 信號運行命令
語法:nohup Command [Arg...] [&]
退出碼:
  126  命令找到但不可執行
  127  nohup 錯誤或命令不存在
  其他 為命令本身退出碼
Copyright © Windows教程網 All Rights Reserved