1. 使用 & 让命令后台运行
在命令末尾加上 &,可以让命令在后台运行,并立即返回终端控制权:
command &
示例:
python3 script.py &
特点:
- 命令会在后台运行,但输出仍然会打印到终端。
- 如果终端关闭,该进程可能会被终止(除非使用 nohup 或 disown)。
2. 使用 nohup 防止进程被终止
nohup(no hang up)可以让命令在终端关闭后继续运行,并将输出重定向到 nohup.out:
nohup command &
示例:
nohup python3 script.py &
特点:
- 即使关闭终端,进程也不会终止。
- 默认输出到 nohup.out,可以用 tail -f nohup.out 查看日志。
3. 使用 disown 让进程脱离终端
如果命令已经在运行(比如用 & 启动),可以把它从当前会话中分离:
# 先启动命令
command &
# 查看进程 ID(PID)
jobs -l
# 脱离终端(假设 PID 是 12345)
disown -h 12345
特点:
- 类似于 nohup,但适用于已经运行的进程。
- 进程不会随终端关闭而终止。
4. 使用 screen 或 tmux 管理后台会话
screen 和 tmux 是终端复用工具,可以创建持久会话,即使断开 SSH 也能恢复:
使用 screen
# 安装 screen(如果未安装)
sudo apt install screen
# 创建新会话
screen -S mysession
# 在会话中运行命令
python3 script.py
# 按 `Ctrl + A`,再按 `D` 脱离会话
# 重新连接会话
screen -r mysession
使用 tmux
# 安装 tmux
sudo apt install tmux
# 创建新会话
tmux new -s mysession
# 运行命令
python3 script.py
# 按 `Ctrl + B`,再按 `D` 脱离会话
# 重新连接会话
tmux attach -t mysession
特点:
- 适合长时间运行的任务(如服务器程序)。
- 可以随时恢复查看输出。
5. 使用 systemd 创建后台服务(适合长期运行)
如果希望命令像系统服务一样运行(开机自启、自动重启),可以创建 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://www.syntaxspace.com/article/2508060938139083.html
评论