温馨提示×

centos怎样后台运行进程

小樊
54
2026-10-09 02:49:01
栏目: 智能运维

在 CentOS(以及其他 Linux 发行版)中,有多种方式可以让进程在后台运行,即使退出终端也不中断。下面按常见程度和使用场景介绍。


一、最基础:命令后加 &

command &

示例:

python app.py &

特点:

  • 进程在后台运行
  • 关闭终端仍可能中断(收到 SIGHUP)

查看后台任务:

jobs

二、退出终端也不中断:nohup

nohup command > output.log 2>&1 &

示例:

nohup python app.py > app.log 2>&1 &

说明:

  • nohup:忽略 SIGHUP 信号
  • > app.log 2>&1:重定向输出
  • &:后台运行

✅ 推荐新手使用


三、setsid(更彻底的后台)

setsid command

示例:

setsid python app.py

特点:

  • 进程不属于当前 shell session
  • 关闭终端完全无影响

四、终端复用工具(强烈推荐)

1. screen

screen
# 在新窗口中运行命令
python app.py
# Ctrl + A 然后按 D 脱离

重新连接:

screen -r

查看会话:

screen -ls

2. tmux(更现代)

tmux
# 运行命令
python app.py
# Ctrl + B 然后按 D 脱离

重新连接:

tmux attach

✅ 服务器长期运行程序首选


五、作为系统服务(生产环境推荐)

使用 systemd

创建服务文件:

vim /etc/systemd/system/myapp.service

示例:

[Unit]
Description=My App
After=network.target

[Service]
ExecStart=/usr/bin/python /opt/app.py
WorkingDirectory=/opt
Restart=always
User=root

[Install]
WantedBy=multi-user.target

启用:

systemctl daemon-reload
systemctl start myapp
systemctl enable myapp

查看状态:

systemctl status myapp

✅ 最稳定、可管理、可开机自启


六、查看后台进程

ps aux | grep command

或:

top
htop

七、常见场景推荐方案

场景 推荐方式
临时跑脚本 nohup ... &
长时间任务 tmux / screen
生产服务 systemd
完全脱离终端 setsid

如果你能告诉我:

  • 运行的是什么程序(Python / Java / Shell)
  • 是否需要开机自启
  • CentOS 版本(7 / 8 / Stream)

我可以给你更精确的命令示例。

0 踩