在 CentOS(以及一般 Linux)上“批量管理进程”,常见场景有:批量启动/停止/重启、批量查看状态、批量杀进程、按规则批量操作。下面按“从简单到专业”给你一套实用方案。
ps -ef | grep nginx
或
pgrep -a nginx
pkill nginx
或
killall nginx
按条件杀(例如运行超过 1 小时):
ps -eo pid,etimes,comm | awk '$2>3600 && $3=="java"{print $1}' | xargs kill -9
for s in nginx php-fpm redis; do
systemctl restart $s
done
如果你用的是 @ 实例服务:
systemctl start myapp@1
systemctl start myapp@2
批量:
systemctl start 'myapp@*'
systemctl list-units --type=service --state=running
systemctl list-units --type=service | grep app | awk '{print $1}' | xargs systemctl stop
示例:批量启动多个程序
#!/bin/bash
apps=(nginx redis mysql)
for app in "${apps[@]}"; do
systemctl restart $app
done
示例:批量检查进程是否存在
for p in nginx redis; do
pgrep $p >/dev/null && echo "$p running" || echo "$p not running"
done
yum install supervisor -y
systemctl enable supervisord
systemctl start supervisord
[program:app1]
command=/opt/app1/run.sh
autostart=true
autorestart=true
supervisorctl start all
supervisorctl stop all
supervisorctl restart all
supervisorctl status
✅ 优点:
如果是多台服务器:
ansible all -m shell -a "systemctl restart nginx"
或 playbook:
- hosts: web
tasks:
- name: restart nginx
systemd:
name: nginx
state: restarted
pssh -h hosts.txt "systemctl restart nginx"
| 场景 | 推荐 |
|---|---|
| 单机少量服务 | systemctl |
| 自研程序 | supervisor |
| 脚本灵活控制 | shell |
| 多台服务器 | Ansible |
| 微服务 | K8s |
如果你能告诉我:
我可以直接给你一套可复制的配置方案。