使用nohup、screen/tmux或systemd可实现Linux进程后台常驻;nohup忽略终端挂断信号,screen/tmux提供会话持久化,systemd用于系统级服务管理,确保开机自启与自动重启。

在Linux环境下,让进程在后台常驻运行,核心思路就是切断它与当前终端的关联,并确保它在终端关闭或用户退出后依然能存活。这通常可以通过几种不同的方式实现,从简单的命令组合到系统级的服务管理,每种方法都有其适用场景和优缺点。
要让一个进程在Linux后台常驻运行,我们通常会用到以下几种方法,它们各有侧重:
最直接的方式是使用
nohup
&
nohup command &
nohup
SIGHUP
&
nohup.out
对于需要更精细控制、甚至在网络断开后还能重新连接会话的场景,
screen
tmux
而对于那些需要作为系统服务,随系统启动而运行,并在崩溃时自动重启的关键应用,
systemd
.service
systemd

这几乎是每个Linux新手都会遇到的困惑,也是理解后台运行机制的关键点。简单来说,当你仅仅使用
command &
SIGHUP
SIGHUP
nohup
nohup
SIGHUP
nohup command &
command
SIGHUP
nohup
nohup.out
那么,如何选择呢?
&
fg
nohup command &
举个例子:
# 仅仅放到后台,关闭终端会终止 sleep 3600 & # 忽略SIGHUP信号,关闭终端会继续运行 nohup sleep 3600 &
实践中,我们通常都会把
nohup
&

screen
tmux
screen
screen
screen -S my_session
my_session
Ctrl+a d
screen -ls
screen -r
screen -r my_session
my_session
Ctrl+a k
tmux
screen
tmux
tmux
tmux new -s my_session
my_session
Ctrl+b d
tmux ls
tmux attach
tmux attach -t my_session
my_session
Ctrl+b %
Ctrl+b "
Ctrl+b x
Ctrl+b c
Ctrl+b n
Ctrl+b p
如何选择?
screen
tmux
tmux
对我个人而言,我更倾向于使用
tmux

对于生产环境中的关键应用,或者任何你希望它作为系统服务运行,并且具备开机自启动、自动重启、统一日志管理等特性的程序,
systemd
要使用
systemd
.service
/etc/systemd/system/
1. 创建 .service
my_app.py
/opt/my_app/
my_app.service
# /etc/systemd/system/my_app.service [Unit] Description=My Custom Application Service After=network.target # 定义服务启动的依赖,例如在网络服务启动后 [Service] User=your_user # 以哪个用户身份运行服务,建议使用非root用户 Group=your_group # 以哪个用户组身份运行 WorkingDirectory=/opt/my_app/ # 服务的运行目录 ExecStart=/usr/bin/python3 /opt/my_app/my_app.py # 启动服务的命令 # ExecStop=/usr/bin/kill -HUP $MAINPID # 如果需要自定义停止命令 Restart=on-failure # 定义重启策略,例如在服务失败时自动重启 RestartSec=5s # 重启前等待5秒 StandardOutput=journal # 将标准输出发送到systemd日志 StandardError=journal # 将标准错误发送到systemd日志 # Environment="MY_VAR=value" # 可以设置环境变量 [Install] WantedBy=multi-user.target # 定义服务在哪个运行级别下启动
解释一下关键配置项:
[Unit]
Description
After
[Service]
User
Group
WorkingDirectory
ExecStart
Restart
on-failure
always
on-success
on-abnormal
RestartSec
StandardOutput
StandardError
journald
journalctl
[Install]
systemd
WantedBy
target
multi-user.target
2. 重新加载systemd配置 创建或修改
.service
systemd
sudo systemctl daemon-reload
3. 启用并启动服务
sudo systemctl enable my_app.service
sudo systemctl start my_app.service
4. 检查服务状态和日志
sudo systemctl status my_app.service
journalctl
sudo journalctl -u my_app.service -f
-f
5. 停止和禁用服务
sudo systemctl stop my_app.service
sudo systemctl disable my_app.service
使用
systemd
systemd
以上就是Linux如何让进程在后台常驻运行的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号