8. 进程管理
8.1 查看进程
bash
# 查看所有进程
ps aux
# 查看当前终端的进程
ps
# 树形显示进程关系
ps auxf
# 查看特定进程
ps aux | grep nginx
# 查看进程树(系统自带)
pstree -pbash
$ ps aux | head -5
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.3 169436 13244 ? Ss Jun19 0:12 /sbin/init
root 2 0.0 0.0 0 0 ? S Jun19 0:00 [kthreadd]
root 3 0.0 0.0 0 0 ? I< Jun19 0:00 [rcu_gp]
root 4 0.0 0.0 0 0 ? I< Jun19 0:00 [rcu_par_gp]top — 实时进程监控
bash
top
# 常用快捷键:M=按内存排序, P=按CPU排序, k=杀进程, q=退出
htop
# 更友好的交互式界面(需安装:sudo apt install htop)bash
top - 10:30:45 up 15:23, 2 users, load average: 0.52, 0.48, 0.35
Tasks: 234 total, 1 running, 233 sleeping, 0 stopped, 0 zombie
%Cpu(s): 5.2 us, 1.3 sy, 0.0 ni, 93.1 id, 0.3 wa, 0.0 hi, 0.1 si
MiB Mem : 4096.0 total, 256.3 free, 2840.5 used, 999.2 buff/cache
MiB Swap: 2048.0 total, 1800.2 free, 247.8 used. 1024.1 avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1234 mysql 20 0 1843652 512340 23456 S 2.3 12.5 10:30.45 mysqld
2345 www-data 20 0 856432 335876 8765 S 0.5 8.2 2:15.23 apache2
3456 user 20 0 987654 115234 5678 S 1.2 2.8 0:15.67 vim8.2 控制进程
bash
# 发送信号给进程
kill PID # 发送 SIGTERM(优雅终止)
kill -9 PID # 发送 SIGKILL(强制终止)
kill -HUP PID # 发送 SIGHUP(重新加载配置)
# 按名称杀进程
killall nginx
pkill -f "python app.py"
# 后台运行命令
long_task &
# 暂停/恢复前台进程
# Ctrl+Z 暂停, bg 恢复到后台, fg 恢复到前台
# nohup — 断开终端后继续运行
nohup ./backup.sh > backup.log 2>&1 &
# 修改进程优先级(-20 最高, 19 最低)
nice -n 10 ./task.sh # 以较低优先级启动
renice 5 -p 1234 # 修改运行中进程的优先级bash
$ nohup ./backup.sh > backup.log 2>&1 &
[1] 5678
$ jobs
[1]+ Running nohup ./backup.sh > backup.log 2>&1 &
$ kill 5678
[1]+ Terminated nohup ./backup.sh > backup.log 2>&1 &8.3 systemctl — 服务管理
bash
# 启动/停止/重启服务
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl reload nginx # 重载配置(不中断服务)
# 查看服务状态
systemctl status nginx
# 设置开机自启
sudo systemctl enable nginx
sudo systemctl disable nginx
# 查看所有服务状态
systemctl list-units --type=service
# 查看失败的服务
systemctl --failedbash
$ systemctl status nginx
● nginx.service - A high performance web server and reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Sat 2026-06-20 10:00:00 CST; 30min ago
Docs: man:nginx(8)
Process: 1234 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; (code=exited, status=0/SUCCESS)
Main PID: 1235 (nginx)
Tasks: 3 (limit: 4915)
Memory: 8.5M
CPU: 120ms
CGroup: /system.slice/nginx.service
├─1235 "nginx: master process /usr/sbin/nginx -g daemon on;"
├─1236 "nginx: worker process"
└─1237 "nginx: worker process"
Jun 20 10:00:00 server systemd[1]: Starting A high performance web server...
Jun 20 10:00:00 server systemd[1]: Started A high performance web server.journalctl — 查看系统日志
bash
# 查看所有日志
journalctl
# 查看特定服务的日志
journalctl -u nginx
# 实时跟踪日志
journalctl -f
# 查看今天的日志
journalctl --since today
# 查看最近 50 行
journalctl -n 50
# 只显示错误
journalctl -p err