在命令末尾加上 &,可以让命令在后台运行,并立即返回终端控制权:
command &
示例:
python3 script.py &
特点:
nohup(no hang up)可以让命令在终端关闭后继续运行,并将输出重定向到 nohup.out:
nohup command &
示例:
nohup python3 script.py &
特点:
如果命令已经在运行(比如用 & 启动),可以把它从当前会话中分离:
# 先启动命令
command &
# 查看进程 ID(PID)
jobs -l
# 脱离终端(假设 PID 是 12345)
disown -h 12345
特点:
screen 和 tmux 是终端复用工具,可以创建持久会话,即使断开 SSH 也能恢复:
# 安装 screen(如果未安装)
sudo apt install screen
# 创建新会话
screen -S mysession
# 在会话中运行命令
python3 script.py
# 按 `Ctrl + A`,再按 `D` 脱离会话
# 重新连接会话
screen -r mysession
# 安装 tmux
sudo apt install tmux
# 创建新会话
tmux new -s mysession
# 运行命令
python3 script.py
# 按 `Ctrl + B`,再按 `D` 脱离会话
# 重新连接会话
tmux attach -t mysession
特点:
如果希望命令像系统服务一样运行(开机自启、自动重启),可以创建 systemd 服务:
sudo nano /etc/systemd/system/my_service.service
写入以下内容:
[Unit]
Description=My Custom Service
[Service]
ExecStart=/usr/bin/python3 /path/to/script.py
WorkingDirectory=/path/to/
Restart=always
User=your_username
[Install]
WantedBy=multi-user.target
然后启用并启动服务:
sudo systemctl enable my_service
sudo systemctl start my_service
查看日志:
journalctl -u my_service -f
方法 | 适用场景 | 终端关闭后是否存活 | 日志管理 |
---|---|---|---|
command & | 临时后台任务 | ❌ 可能被终止 | 输出到终端 |
nohup command & | 长期运行,简单方式 | ✔️ 存活 | 输出到 nohup.out |
disown | 已运行的进程脱离终端 | ✔️ 存活 | 需手动重定向 |
screen/tmux | 交互式后台任务 | ✔️ 存活 | 可随时查看 |
systemd | 系统级服务 | ✔️ 存活 | 用 journalctl 查看 |
选择合适的方式取决于你的需求!
https://blog.xqlee.com/article/2508060938139083.html